tabled_derive/
attributes.rs
1use syn::{Attribute, LitInt};
2
3use crate::{casing_style::CasingStyle, error::Error, parse};
4
5#[derive(Debug, Default)]
6pub struct Attributes {
7 pub is_ignored: bool,
8 pub inline: bool,
9 pub inline_prefix: Option<String>,
10 pub rename: Option<String>,
11 pub rename_all: Option<CasingStyle>,
12 pub display_with: Option<String>,
13 pub display_with_use_self: bool,
14 pub order: Option<usize>,
15}
16
17impl Attributes {
18 pub fn parse(attrs: &[Attribute]) -> Result<Self, Error> {
19 let mut attributes = Self::default();
20 attributes.fill_attributes(attrs)?;
21
22 Ok(attributes)
23 }
24
25 fn fill_attributes(&mut self, attrs: &[Attribute]) -> Result<(), Error> {
26 for attrs in parse::parse_attributes(attrs) {
27 let attrs = attrs?;
28 for attr in attrs {
29 self.insert_attribute(attr)?;
30 }
31 }
32
33 Ok(())
34 }
35
36 fn insert_attribute(&mut self, attr: parse::TabledAttr) -> Result<(), Error> {
37 match attr.kind {
38 parse::TabledAttrKind::Skip(b) => {
39 if b.value {
40 self.is_ignored = true;
41 }
42 }
43 parse::TabledAttrKind::Inline(b, prefix) => {
44 if b.value {
45 self.inline = true;
46 }
47
48 if let Some(prefix) = prefix {
49 self.inline_prefix = Some(prefix.value());
50 }
51 }
52 parse::TabledAttrKind::Rename(value) => self.rename = Some(value.value()),
53 parse::TabledAttrKind::RenameAll(lit) => {
54 self.rename_all = Some(CasingStyle::from_lit(&lit)?);
55 }
56 parse::TabledAttrKind::DisplayWith(path, use_self) => {
57 self.display_with = Some(path.value());
58 self.display_with_use_self = use_self;
59 }
60 parse::TabledAttrKind::Order(value) => self.order = Some(lit_int_to_usize(&value)?),
61 }
62
63 Ok(())
64 }
65
66 pub fn is_ignored(&self) -> bool {
67 self.is_ignored
68 }
69}
70
71pub struct ObjectAttributes {
72 pub rename_all: Option<CasingStyle>,
73}
74
75impl ObjectAttributes {
76 pub fn parse(attrs: &[Attribute]) -> Result<Self, Error> {
77 let attrs = Attributes::parse(attrs)?;
78 Ok(Self {
79 rename_all: attrs.rename_all,
80 })
81 }
82}
83
84fn lit_int_to_usize(value: &LitInt) -> Result<usize, Error> {
85 value.base10_parse::<usize>().map_err(|e| {
86 Error::new(
87 format!("Failed to parse {:?} as usize; {}", value.to_string(), e),
88 value.span(),
89 None,
90 )
91 })
92}