Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 extern crate proc_macro;
2 use proc_macro::TokenStream;
3 use quote::quote;
4 use syn::{parse_macro_input, DeriveInput};
5 use syn::{Type, TypePath};
6
7 fn is_option(ty: &syn::Type) -> bool {
8 if let Type::Path(TypePath { path, .. }) = ty {
9 if let Some(segment) = path.segments.last() {
10 return segment.ident == "Option";
11 }
12 }
13 false
14 }
15
16 /// Generate code to format a field value based on its FieldType
17 fn apply_field_formatting(
18 field_type: Option<FieldType>,
19 field_name: &str,
20 ) -> proc_macro2::TokenStream {
21 match field_type {
22 Some(FieldType::SingleLine) => quote! {
23 deb822_fast::convert::format_single_line(&value, #field_name)
24 },
25 Some(FieldType::MultiLine) => quote! {
26 deb822_fast::convert::format_multi_line(&value)
27 },
28 Some(FieldType::Folded) => quote! {
29 deb822_fast::convert::format_folded(&value)
30 },
31 None => quote! { value },
32 }
33 }
34
35 // Generate `from_paragraph`, ``to_paragraph`` methods for the annotated struct, i.e.:
36 //
37 // ```rust
38 // #[derive(FromDeb822)]
39 // struct X {
40 // a: i32,
41 // b: i32,
42 // c: Option<String>,
43 // d: Vec<String>,
44 // #[deb822(field = "E")]
45 // e: bool,
46 // }
47 // ```
48 //
49 // will generate:
50 //
51 // ```rust
52 //
53 // impl<P: deb822_fast::convert::Deb822LikeParagraph> FromDeb822Paragraph<P> for X {
54 // fn from_paragraph(para: &P) -> Result<Self, String> {
55 // Ok(Self {
56 // a: para.get("a").ok_or_else(|| "missing field: a")?.parse().map_err(|e| format!("parsing field a: {}", e))?,
57 // b: para.get("b").ok_or_else(|| "missing field: b")?.parse().map_err(|e| format!("parsing field b: {}", e))?,
58 // c: para.get("c").map(|v| v.parse().map_err(|e| format!("parsing field c: {}", e))).transpose()?,
59 // d: para.get("d").ok_or_else(|| "missing field: d")?.split_whitespace().map(|s| s.to_string()).collect(),
60 // e: para.get("E").ok_or_else(|| "missing field: e")?.parse().map_err(|e| format!("parsing field E: {}", e))?,
61 // })
62 // }
63 //
64 // And:
65 //
66 // ```rust
67 // #[derive(ToDeb822)]
68 // struct X {
69 // a: i32,
70 // b: i32,
71 // c: Option<String>,
72 // d: Vec<String>,
73 // #[deb822(field = "E")]
74 // e: bool,
75 // }
76 // ```
77 //
78 // will generate:
79 //
80 // ```rust
81 // impl<P: deb822_fast::convert::Deb822LikeParagraph> ToDeb822Paragraph<P> for X {
82 // fn to_paragraph(&self) -> P {
83 // let mut fields = Vec::<(String, String)>::new();
84 // fields.set("a", self.a.to_string());
85 // fields.set("b", self.b.to_string());
86 // if let Some(v) = &self.c {
87 // fields.set("c", v.to_string());
88 // }
89 // fields.set("d", self.d.join(" "));
90 // fields.set("E", self.e.to_string());
91 // deb822_fast::Paragraph::from(fields)
92 // }
93 //
94 // fn update_paragraph(&self, para: &mut deb822_fast::Paragraph) {
95 // para.set("a", &self.a.to_string());
96 // para.set("b", &self.b.to_string());
97 // if let Some(v) = &self.c {
98 // para.set("c", &v.to_string());
99 // } else {
100 // para.remove("c");
101 // }
102 // para.set("d", &self.d.join(" "));
103 // para.set("E", &self.e.to_string());
104 // }
105 // }
106 // ```
107
108 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
109 enum FieldType {
110 SingleLine,
111 MultiLine,
112 Folded,
113 }
114
115 struct FieldAttributes {
116 field: Option<String>,
117 serialize_with: Option<syn::ExprPath>,
118 deserialize_with: Option<syn::ExprPath>,
119 field_type: Option<FieldType>,
120 }
121
122 fn extract_field_attributes(attrs: &[syn::Attribute]) -> Result<FieldAttributes, syn::Error> {
123 let mut field = None;
124 let mut serialize_with = None;
125 let mut deserialize_with = None;
126 let mut field_type = None;
127
128 for attr in attrs {
129 if !attr.path().is_ident("deb822") {
130 continue;
131 }
132
133 // Parse the attribute arguments
134 attr.parse_nested_meta(|meta| {
135 if meta.path.is_ident("field") {
136 let value = meta.value()?;
137 let s: syn::LitStr = value.parse()?;
138 field = Some(s.value());
139 Ok(())
140 } else if meta.path.is_ident("serialize_with") {
141 let value = meta.value()?;
142 let path: syn::ExprPath = value.parse()?;
143 serialize_with = Some(path);
144 Ok(())
145 } else if meta.path.is_ident("deserialize_with") {
146 let value = meta.value()?;
147 let path: syn::ExprPath = value.parse()?;
148 deserialize_with = Some(path);
149 Ok(())
150 } else if meta.path.is_ident("folded") {
151 if field_type.is_some() {
152 return Err(meta.error(
153 "only one of 'folded', 'single_line', or 'multi_line' can be specified",
154 ));
155 }
156 field_type = Some(FieldType::Folded);
157 Ok(())
158 } else if meta.path.is_ident("single_line") {
159 if field_type.is_some() {
160 return Err(meta.error(
161 "only one of 'folded', 'single_line', or 'multi_line' can be specified",
162 ));
163 }
164 field_type = Some(FieldType::SingleLine);
165 Ok(())
166 } else if meta.path.is_ident("multi_line") {
167 if field_type.is_some() {
168 return Err(meta.error(
169 "only one of 'folded', 'single_line', or 'multi_line' can be specified",
170 ));
171 }
172 field_type = Some(FieldType::MultiLine);
173 Ok(())
174 } else {
175 Err(meta.error(format!(
176 "unsupported attribute: {}",
177 meta.path.get_ident().unwrap()
178 )))
179 }
180 })?;
181 }
182
183 Ok(FieldAttributes {
184 field,
185 serialize_with,
186 deserialize_with,
187 field_type,
188 })
189 }
190
191 #[proc_macro_derive(FromDeb822, attributes(deb822))]
192 pub fn derive_from_deb822(input: TokenStream) -> TokenStream {
193 let input = parse_macro_input!(input as DeriveInput);
194 let name = &input.ident;
195
196 let s = if let syn::Data::Struct(s) = &input.data {
197 s
198 } else {
199 panic!("FromDeb822 can only be derived for structs")
200 };
201
202 let from_fields = s.fields.iter().map(|f| {
203 let attrs = extract_field_attributes(&f.attrs).unwrap();
204 let ident = &f.ident;
205 // Get key either from the #[deb822(field = "foo")] attribute, or derive it from the
206 // field name
207 let key = attrs.field.unwrap_or_else(||ident.as_ref().unwrap().to_string());
208 let deserialize_with = if let Some(deserialize_with) = attrs.deserialize_with {
209 quote! { #deserialize_with }
210 } else {
211 quote! { std::str::FromStr::from_str }
212 };
213 // Check if the field is optional or not
214 let ty = &f.ty;
215 let is_option = is_option(ty);
216
217 if is_option {
218 // Allow the field to be missing
219 quote! {
220 #ident: para.get(#key).map(|v| #deserialize_with(&v).map_err(|e| format!("parsing field {}: {}", #key, e))).transpose()?
221 }
222 } else {
223 // The field is required
224 quote! {
225 #ident: #deserialize_with(&para.get(#key).ok_or_else(|| format!("missing field: {}", #key))?).map_err(|e| format!("parsing field {}: {}", #key, e))?
226 }
227 }
228 }).collect::<Vec<_>>();
229
230 let gen = quote! {
231 impl<P: deb822_fast::convert::Deb822LikeParagraph> deb822_fast::FromDeb822Paragraph<P> for #name {
232 fn from_paragraph(para: &P) -> Result<Self, String> {
233 Ok(Self {
234 #(#from_fields,)*
235 })
236 }
237 }
238 };
239 gen.into()
240 }
241
242 #[proc_macro_derive(ToDeb822, attributes(deb822))]
243 pub fn derive_to_deb822(input: TokenStream) -> TokenStream {
244 let input = parse_macro_input!(input as DeriveInput);
245 let name = &input.ident;
246
247 let s = if let syn::Data::Struct(s) = &input.data {
248 s
249 } else {
250 panic!("Deb822 can only be derived for structs")
251 };
252
253 let mut to_fields = vec![];
254 let mut update_fields = vec![];
255
256 for f in s.fields.iter() {
257 let attrs = extract_field_attributes(&f.attrs).unwrap();
258 let ident = &f.ident;
259 let key = attrs
260 .field
261 .unwrap_or_else(|| ident.as_ref().unwrap().to_string());
262 let serialize_with = if let Some(serialize_with) = attrs.serialize_with {
263 quote! { #serialize_with }
264 } else {
265 quote! { ToString::to_string }
266 };
267
268 let field_type = attrs.field_type;
269 let format_value = apply_field_formatting(field_type, &key);
270
271 let ty = &f.ty;
272 let is_option = is_option(ty);
273
274 to_fields.push(if is_option {
275 quote! {
276 if let Some(v) = &self.#ident {
277 let value = #serialize_with(&v);
278 let formatted = #format_value;
279 fields.push((#key.to_string(), formatted));
280 }
281 }
282 } else {
283 quote! {
284 let value = #serialize_with(&self.#ident);
285 let formatted = #format_value;
286 fields.push((#key.to_string(), formatted));
287 }
288 });
289
290 update_fields.push(if is_option {
291 quote! {
292 if let Some(v) = &self.#ident {
293 let value = #serialize_with(&v);
294 let formatted = #format_value;
295 para.set(#key, formatted.as_str());
296 } else {
297 para.remove(#key);
298 }
299 }
300 } else {
301 quote! {
302 let value = #serialize_with(&self.#ident);
303 let formatted = #format_value;
304 para.set(#key, formatted.as_str());
305 }
306 });
307 }
308
309 let gen = quote! {
310 impl<P: deb822_fast::convert::Deb822LikeParagraph> deb822_fast::ToDeb822Paragraph<P> for #name {
311 fn to_paragraph(&self) -> P {
312 let mut fields = Vec::<(String, String)>::new();
313 #(#to_fields)*
314 fields.into_iter().collect()
315 }
316
317 fn update_paragraph(&self, para: &mut P) {
318 #(#update_fields)*
319 }
320 }
321 };
322 gen.into()
323 }