Helper method used to parse out any `rename` attribute definitions in a struct marked with the ToMap trait, returning a mapping between the original field name and the one being changed for later use when doing codegen.
(fields: &Fields)
| 172 | /// marked with the ToMap trait, returning a mapping between the original field name |
| 173 | /// and the one being changed for later use when doing codegen. |
| 174 | fn parse_rename_attrs(fields: &Fields) -> BTreeMap<String, String> { |
| 175 | let mut rename: BTreeMap<String, String> = BTreeMap::new(); |
| 176 | |
| 177 | // != for if let not yet introduced |
| 178 | if let Fields::Named(_) = fields { |
| 179 | // no-op |
| 180 | } else { |
| 181 | panic!("Must have named fields."); |
| 182 | } |
| 183 | |
| 184 | // iterate over fields available and attributes |
| 185 | for field in fields.iter() { |
| 186 | for attr in field.attrs.iter() { |
| 187 | // parse original struct field name |
| 188 | let field_name = field.ident.as_ref().unwrap().to_string(); |
| 189 | if rename.contains_key(&field_name) { |
| 190 | panic!("Cannot redefine field name multiple times."); |
| 191 | } |
| 192 | |
| 193 | // parse out name value pairs in attributes |
| 194 | // first get `lst` in #[rename(lst)] |
| 195 | match attr.parse_meta() { |
| 196 | Ok(syn::Meta::List(lst)) => { |
| 197 | // then parse key-value name |
| 198 | match lst.nested.first() { |
| 199 | Some(syn::NestedMeta::Meta(syn::Meta::NameValue(nm))) => { |
| 200 | // check path to be = `name` |
| 201 | let path = nm.path.get_ident().unwrap().to_string(); |
| 202 | if path != "name" { |
| 203 | panic!("{}", RENAME_ERROR_MSG); |
| 204 | } |
| 205 | |
| 206 | let lit = match &nm.lit { |
| 207 | syn::Lit::Str(val) => val.value(), |
| 208 | _ => { |
| 209 | panic!("{}", RENAME_ERROR_MSG); |
| 210 | } |
| 211 | }; |
| 212 | rename.insert(field_name, lit); |
| 213 | } |
| 214 | _ => { |
| 215 | panic!("{}", RENAME_ERROR_MSG); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | _ => { |
| 220 | panic!("{}", RENAME_ERROR_MSG); |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | rename |
| 226 | } |