pilota_build2/plugin/
serde.rs1use crate::tags::{EnumMode, SerdeAttribute};
2
3#[derive(Clone, Copy)]
4pub struct SerdePlugin;
5
6impl crate::Plugin for SerdePlugin {
7 fn on_item(
8 &mut self,
9 cx: &crate::Context,
10 def_id: crate::DefId,
11 item: std::sync::Arc<crate::rir::Item>,
12 ) {
13 let attribute = cx
14 .node_tags(def_id)
15 .and_then(|tags| tags.get::<SerdeAttribute>().cloned());
16
17 match &*item {
18 crate::rir::Item::Message(_)
19 | crate::rir::Item::Enum(_)
20 | crate::rir::Item::NewType(_) => {
21 cx.with_adjust_mut(def_id, |adj| {
22 adj.add_attrs(&[
23 "#[derive(::pilota::serde::Serialize, ::pilota::serde::Deserialize)]"
24 .into(),
25 ]);
26 if let Some(attribute) = attribute {
27 let attr = attribute.0.to_string().replace('\\', "");
28 adj.add_attrs(&[attr.into()]);
29 }
30 });
31
32 if cx.node_tags(def_id).unwrap().get::<EnumMode>().copied()
33 == Some(EnumMode::NewType)
34 {
35 cx.with_adjust_mut(def_id, |adj| {
36 adj.add_attrs(&["#[serde(transparent)]".into()]);
37 })
38 }
39 }
40 _ => {}
41 };
42 crate::plugin::walk_item(self, cx, def_id, item)
43 }
44
45 fn on_field(
46 &mut self,
47 cx: &crate::Context,
48 def_id: crate::DefId,
49 f: std::sync::Arc<crate::rir::Field>,
50 ) {
51 if let Some(attribute) = cx
52 .tags(f.tags_id)
53 .and_then(|tags| tags.get::<SerdeAttribute>().cloned())
54 {
55 let attr = attribute.0.replace('\\', "");
56 cx.with_adjust_mut(def_id, |adj| adj.add_attrs(&[attr.into()]))
57 }
58 }
59
60 fn on_variant(
61 &mut self,
62 cx: &crate::Context,
63 def_id: crate::DefId,
64 variant: std::sync::Arc<crate::rir::EnumVariant>,
65 ) {
66 if let Some(attribute) = cx
67 .node_tags(variant.did)
68 .and_then(|tags| tags.get::<SerdeAttribute>().cloned())
69 {
70 let attr = attribute.0.replace('\\', "");
71 cx.with_adjust_mut(def_id, |adj| adj.add_attrs(&[attr.into()]))
72 }
73 }
74}