| 1 | use crate::attribute::AttributeValue; |
| 2 | use crate::{internal, util}; |
| 3 | |
| 4 | use proc_macro::TokenStream; |
| 5 | use proc_macro2::{Ident, Span}; |
| 6 | use quote::{format_ident, quote, quote_spanned, ToTokens}; |
| 7 | use syn::parse::Parse; |
| 8 | use syn::spanned::Spanned; |
| 9 | use syn::{Attribute, Data, DataStruct, DeriveInput, Field, Fields, Type}; |
| 10 | |
| 11 | #[derive(Default)] |
| 12 | pub struct InternalFileDetails { |
| 13 | pub(crate) has_internal_write_module: bool, |
| 14 | pub(crate) has_internal_file_type: bool, |
| 15 | pub(crate) id3v2_strippable: bool, |
| 16 | } |
| 17 | |
| 18 | #[derive(Default)] |
| 19 | pub(crate) struct FileFields { |
| 20 | pub(crate) tags: Vec<FieldContents>, |
| 21 | pub(crate) properties: Option<Field>, |
| 22 | } |
| 23 | |
| 24 | pub struct FileStructInfo { |
| 25 | pub(crate) name: Ident, |
| 26 | pub(crate) span: Span, |
| 27 | pub(crate) fields: FileFields, |
| 28 | } |
| 29 | |
| 30 | pub(crate) struct AudioFileImplFields { |
| 31 | pub(crate) should_impl_audiofile: bool, |
| 32 | pub(crate) read_fn: Option<proc_macro2::TokenStream>, |
| 33 | pub(crate) write_fn: Option<proc_macro2::TokenStream>, |
| 34 | } |
| 35 | |
| 36 | impl Default for AudioFileImplFields { |
| 37 | fn default() -> Self { |
| 38 | Self { |
| 39 | should_impl_audiofile: true, |
| 40 | read_fn: None, |
| 41 | write_fn: None, |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub struct LoftyFile { |
| 47 | pub(crate) struct_info: FileStructInfo, |
| 48 | pub(crate) audiofile_impl: AudioFileImplFields, |
| 49 | pub(crate) internal_details: InternalFileDetails, |
| 50 | pub(crate) file_type: proc_macro2::TokenStream, |
| 51 | pub(crate) should_impl_into_taggedfile: bool, |
| 52 | } |
| 53 | |
| 54 | impl Parse for LoftyFile { |
| 55 | fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { |
| 56 | let input: DeriveInput = input.parse()?; |
| 57 | |
| 58 | let data_struct = match input.data { |
| 59 | Data::Struct( |
| 60 | ref data_struct @ DataStruct { |
| 61 | fields: Fields::Named(_), |
| 62 | .. |
| 63 | }, |
| 64 | ) => data_struct, |
| 65 | _ => { |
| 66 | return Err(util::err( |
| 67 | input.ident.span(), |
| 68 | "This macro can only be used on structs with named fields", |
| 69 | )) |
| 70 | }, |
| 71 | }; |
| 72 | |
| 73 | let mut lofty_file = LoftyFile { |
| 74 | struct_info: FileStructInfo { |
| 75 | name: input.ident.clone(), |
| 76 | span: input.ident.span(), |
| 77 | fields: FileFields::default(), |
| 78 | }, |
| 79 | audiofile_impl: AudioFileImplFields::default(), |
| 80 | should_impl_into_taggedfile: true, |
| 81 | file_type: proc_macro2::TokenStream::new(), |
| 82 | internal_details: InternalFileDetails::default(), |
| 83 | }; |
| 84 | |
| 85 | let mut errors = Vec::new(); |
| 86 | |
| 87 | let mut has_internal_write_module = false; |
| 88 | for attr in &input.attrs { |
| 89 | if let Some(lofty_attr) = AttributeValue::from_attribute("lofty", attr)? { |
| 90 | match lofty_attr { |
| 91 | AttributeValue::Path(value) => match &*value.to_string() { |
| 92 | "no_audiofile_impl" => { |
| 93 | lofty_file.audiofile_impl.should_impl_audiofile = false |
| 94 | }, |
| 95 | "no_into_taggedfile_impl" => lofty_file.should_impl_into_taggedfile = false, |
| 96 | "internal_write_module_do_not_use_anywhere_else" => { |
| 97 | has_internal_write_module = true |
| 98 | }, |
| 99 | _ => errors.push(util::err(attr.span(), "Unknown attribute")), |
| 100 | }, |
| 101 | AttributeValue::NameValue(lhs, rhs) => match &*lhs.to_string() { |
| 102 | "read_fn" => lofty_file.audiofile_impl.read_fn = Some(rhs.parse()?), |
| 103 | "write_fn" => lofty_file.audiofile_impl.write_fn = Some(rhs.parse()?), |
| 104 | "file_type" => lofty_file.file_type = rhs.parse()?, |
| 105 | _ => errors.push(util::err(attr.span(), "Unknown attribute")), |
| 106 | }, |
| 107 | _ => errors.push(util::err(attr.span(), "Unknown attribute")), |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | let struct_name = input.ident.clone(); |
| 113 | let opt_file_type = internal::opt_internal_file_type(struct_name.to_string()); |
| 114 | |
| 115 | let has_internal_file_type = opt_file_type.is_some(); |
| 116 | if !has_internal_file_type && has_internal_write_module { |
| 117 | // TODO: This is the best check we can do for now I think? |
| 118 | // Definitely needs some work when a better solution comes out. |
| 119 | return Err(crate::util::err( |
| 120 | input.ident.span(), |
| 121 | "Attempted to use an internal attribute externally", |
| 122 | )); |
| 123 | } |
| 124 | |
| 125 | lofty_file.internal_details.has_internal_write_module = has_internal_write_module; |
| 126 | lofty_file.internal_details.has_internal_file_type = has_internal_file_type; |
| 127 | |
| 128 | // Internal files do not specify a `#[lofty(file_type = "...")]` |
| 129 | if lofty_file.file_type.is_empty() && lofty_file.internal_details.has_internal_file_type { |
| 130 | let Some((ft, id3v2_strip)) = opt_file_type else { |
| 131 | return Err(util::err( |
| 132 | input.ident.span(), |
| 133 | "Unable to locate file type for internal file", |
| 134 | )); |
| 135 | }; |
| 136 | |
| 137 | lofty_file.internal_details.id3v2_strippable = id3v2_strip; |
| 138 | lofty_file.file_type = ft; |
| 139 | } |
| 140 | |
| 141 | let (tag_fields, properties_field) = match get_fields(&mut errors, data_struct)? { |
| 142 | Some(fields) => fields, |
| 143 | None => return Err(errors.remove(0)), |
| 144 | }; |
| 145 | |
| 146 | if tag_fields.is_empty() { |
| 147 | errors.push(util::err(input.ident.span(), "Struct has no tag fields")); |
| 148 | } |
| 149 | |
| 150 | // We do not need to check for a `properties` field yet. |
| 151 | lofty_file.struct_info.fields.tags = tag_fields; |
| 152 | lofty_file.struct_info.fields.properties = properties_field.cloned(); |
| 153 | |
| 154 | Ok(lofty_file) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | impl LoftyFile { |
| 159 | pub(crate) fn emit(self) -> syn::Result<TokenStream> { |
| 160 | // When implementing `AudioFile`, the struct must have: |
| 161 | // * A `properties` field |
| 162 | // * A `#[read_fn]` attribute |
| 163 | // |
| 164 | // Otherwise, we can simply ignore their absence. |
| 165 | let mut audiofile_impl = proc_macro2::TokenStream::new(); |
| 166 | if self.audiofile_impl.should_impl_audiofile { |
| 167 | audiofile_impl = generate_audiofile_impl(&self)?; |
| 168 | } |
| 169 | |
| 170 | // Assert all tag fields implement `TagExt` |
| 171 | let assert_tag_impl_into = self |
| 172 | .struct_info |
| 173 | .fields |
| 174 | .tags |
| 175 | .iter() |
| 176 | .enumerate() |
| 177 | .map(|(i, f)| { |
| 178 | let name = format_ident!("_AssertTagExt{}", i); |
| 179 | let field_ty = &f.ty; |
| 180 | quote_spanned! {field_ty.span()=> |
| 181 | struct #name where #field_ty: ::lofty::prelude::TagExt; |
| 182 | } |
| 183 | }); |
| 184 | |
| 185 | let mut from_taggedfile_impl = proc_macro2::TokenStream::new(); |
| 186 | if self.should_impl_into_taggedfile { |
| 187 | from_taggedfile_impl = generate_from_taggedfile_impl(&self); |
| 188 | } |
| 189 | |
| 190 | let getters = get_getters(&self.struct_info.fields.tags, &self.struct_info.name); |
| 191 | |
| 192 | let mut ret = quote! { |
| 193 | #( #assert_tag_impl_into )* |
| 194 | |
| 195 | #audiofile_impl |
| 196 | |
| 197 | #from_taggedfile_impl |
| 198 | |
| 199 | #( #getters )* |
| 200 | }; |
| 201 | |
| 202 | // Create `write` module if internal |
| 203 | if self.internal_details.has_internal_write_module { |
| 204 | let lookup = internal::init_write_lookup(self.internal_details.id3v2_strippable); |
| 205 | let write_mod = internal::write_module(&self.struct_info.fields.tags, lookup); |
| 206 | |
| 207 | ret = quote! { |
| 208 | #ret |
| 209 | |
| 210 | use crate::_this_is_internal; |
| 211 | |
| 212 | #write_mod |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | Ok(TokenStream::from(ret)) |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | pub(crate) struct FieldContents { |
| 221 | name: Ident, |
| 222 | pub(crate) attrs: Vec<Attribute>, |
| 223 | needs_option: bool, |
| 224 | getter_name: Option<proc_macro2::TokenStream>, |
| 225 | ty: Type, |
| 226 | pub(crate) tag_type: proc_macro2::TokenStream, |
| 227 | } |
| 228 | |
| 229 | impl FieldContents { |
| 230 | pub(crate) fn get_cfg_features(&self) -> impl Iterator<Item = &Attribute> { |
| 231 | self.attrs.iter().filter(|a| a.path().is_ident("cfg")) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | fn get_fields<'a>( |
| 236 | errors: &mut Vec<syn::Error>, |
| 237 | data: &'a DataStruct, |
| 238 | ) -> syn::Result<Option<(Vec<FieldContents>, Option<&'a syn::Field>)>> { |
| 239 | let mut tag_fields = Vec::new(); |
| 240 | let mut properties_field = None; |
| 241 | |
| 242 | for field in &data.fields { |
| 243 | let name = field.ident.clone().unwrap(); |
| 244 | |
| 245 | if name == "properties" { |
| 246 | properties_field = Some(field); |
| 247 | } |
| 248 | |
| 249 | if !name.to_string().ends_with("_tag") { |
| 250 | continue; |
| 251 | } |
| 252 | |
| 253 | let mut tag_type = None; |
| 254 | let mut getter_name = None; |
| 255 | for attr in &field.attrs { |
| 256 | if let Some(lofty_attr) = AttributeValue::from_attribute("lofty", attr)? { |
| 257 | match lofty_attr { |
| 258 | AttributeValue::NameValue(lhs, rhs) => match &*lhs.to_string() { |
| 259 | "tag_type" => tag_type = Some(rhs.parse::<proc_macro2::TokenStream>()?), |
| 260 | "getter" => getter_name = Some(rhs.parse::<proc_macro2::TokenStream>()?), |
| 261 | _ => errors.push(util::err(attr.span(), "Unknown attribute")), |
| 262 | }, |
| 263 | _ => errors.push(util::err(attr.span(), "Unknown attribute")), |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | let Some(tag_type) = tag_type else { |
| 269 | errors.push(util::err( |
| 270 | field.ident.span(), |
| 271 | "Expected a `#[lofty(tag_type = \"...\")]` attribute", |
| 272 | )); |
| 273 | |
| 274 | return Ok(None); |
| 275 | }; |
| 276 | |
| 277 | let other_attrs = field |
| 278 | .attrs |
| 279 | .iter() |
| 280 | .filter(|a| !a.path().is_ident("lofty")) |
| 281 | .cloned() |
| 282 | .collect::<Vec<_>>(); |
| 283 | |
| 284 | let option_unwrapped = util::extract_type_from_option(&field.ty); |
| 285 | // `option_unwrapped` will be `Some` if the type was wrapped in an `Option` |
| 286 | let needs_option = option_unwrapped.is_some(); |
| 287 | |
| 288 | let contents = FieldContents { |
| 289 | name, |
| 290 | attrs: other_attrs, |
| 291 | getter_name, |
| 292 | ty: option_unwrapped.unwrap_or_else(|| field.ty.clone()), |
| 293 | tag_type, |
| 294 | needs_option, |
| 295 | }; |
| 296 | tag_fields.push(contents); |
| 297 | } |
| 298 | |
| 299 | Ok(Some((tag_fields, properties_field))) |
| 300 | } |
| 301 | |
| 302 | fn get_getters<'a>( |
| 303 | tag_fields: &'a [FieldContents], |
| 304 | struct_name: &'a Ident, |
| 305 | ) -> impl Iterator<Item = proc_macro2::TokenStream> + 'a { |
| 306 | tag_fields.iter().map(move |f| { |
| 307 | let name = f.getter_name.clone().unwrap_or_else(|| { |
| 308 | let name = f.name.to_string().strip_suffix("_tag").unwrap().to_string(); |
| 309 | |
| 310 | Ident::new(&name, f.name.span()).into_token_stream() |
| 311 | }); |
| 312 | |
| 313 | let (ty_prefix, ty_suffix) = if f.needs_option { |
| 314 | (quote! {Option<}, quote! {>}) |
| 315 | } else { |
| 316 | (quote! {}, quote! {}) |
| 317 | }; |
| 318 | |
| 319 | let field_name = &f.name; |
| 320 | let field_ty = &f.ty; |
| 321 | |
| 322 | let ref_access = if f.needs_option { |
| 323 | quote! {self.#field_name.as_ref()} |
| 324 | } else { |
| 325 | quote! {&self.#field_name} |
| 326 | }; |
| 327 | |
| 328 | let mut_ident = Ident::new(&format!("{}_mut", name), Span::call_site()); |
| 329 | |
| 330 | let mut_access = if f.needs_option { |
| 331 | quote! {self.#field_name.as_mut()} |
| 332 | } else { |
| 333 | quote! {&mut self.#field_name} |
| 334 | }; |
| 335 | |
| 336 | let set_ident = Ident::new(&format!("set_{}", name), Span::call_site()); |
| 337 | |
| 338 | let setter = if f.needs_option { |
| 339 | quote! { |
| 340 | let ret = self.#field_name.take(); |
| 341 | self.#field_name = Some(tag); |
| 342 | return ret; |
| 343 | } |
| 344 | } else { |
| 345 | quote! { |
| 346 | Some(::core::mem::replace(&mut self.#field_name, tag)) |
| 347 | } |
| 348 | }; |
| 349 | |
| 350 | let remove_ident = Ident::new(&format!("remove_{}", name), Span::call_site()); |
| 351 | |
| 352 | let remover = if f.needs_option { |
| 353 | quote! { self.#field_name.take() } |
| 354 | } else { |
| 355 | let assert_field_ty_default = quote_spanned! {f.name.span()=> |
| 356 | struct _AssertDefault where #field_ty: core::default::Default; |
| 357 | }; |
| 358 | |
| 359 | quote! { |
| 360 | #assert_field_ty_default |
| 361 | ::core::mem::take(&mut self.#field_name) |
| 362 | } |
| 363 | }; |
| 364 | |
| 365 | let cfg_features = f.get_cfg_features(); |
| 366 | quote! { |
| 367 | #( #cfg_features )* |
| 368 | impl #struct_name { |
| 369 | /// Returns a reference to the tag |
| 370 | pub fn #name(&self) -> #ty_prefix &#field_ty #ty_suffix { |
| 371 | #ref_access |
| 372 | } |
| 373 | |
| 374 | /// Returns a mutable reference to the tag |
| 375 | pub fn #mut_ident(&mut self) -> #ty_prefix &mut #field_ty #ty_suffix { |
| 376 | #mut_access |
| 377 | } |
| 378 | |
| 379 | /// Sets the tag, returning the old one |
| 380 | pub fn #set_ident(&mut self, tag: #field_ty) -> Option<#field_ty> { |
| 381 | #setter |
| 382 | } |
| 383 | |
| 384 | /// Removes the tag |
| 385 | pub fn #remove_ident(&mut self) -> #ty_prefix #field_ty #ty_suffix { |
| 386 | #remover |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | }) |
| 391 | } |
| 392 | |
| 393 | fn generate_audiofile_impl(file: &LoftyFile) -> syn::Result<proc_macro2::TokenStream> { |
| 394 | fn tag_exists_iter( |
| 395 | tag_fields: &[FieldContents], |
| 396 | ) -> impl Iterator<Item = proc_macro2::TokenStream> + '_ { |
| 397 | tag_fields.iter().map(|f| { |
| 398 | let name = &f.name; |
| 399 | if f.needs_option { |
| 400 | quote! { self.#name.is_some() } |
| 401 | } else { |
| 402 | quote! { true } |
| 403 | } |
| 404 | }) |
| 405 | } |
| 406 | |
| 407 | let Some(properties_field) = &file.struct_info.fields.properties else { |
| 408 | return Err(util::err( |
| 409 | file.struct_info.span, |
| 410 | "Struct has no `properties` field, required for `AudioFile` impl", |
| 411 | )); |
| 412 | }; |
| 413 | |
| 414 | let Some(read_fn) = &file.audiofile_impl.read_fn else { |
| 415 | return Err(util::err( |
| 416 | file.struct_info.span, |
| 417 | "Expected a `#[read_fn]` attribute", |
| 418 | )); |
| 419 | }; |
| 420 | |
| 421 | let tag_fields = &file.struct_info.fields.tags; |
| 422 | |
| 423 | let save_to_body = get_save_to_body(file.audiofile_impl.write_fn.as_ref(), tag_fields); |
| 424 | |
| 425 | let tag_exists = tag_exists_iter(tag_fields); |
| 426 | let tag_exists_2 = tag_exists_iter(tag_fields); |
| 427 | |
| 428 | let tag_type = tag_fields.iter().map(|f| &f.tag_type); |
| 429 | |
| 430 | let properties_field_ty = &properties_field.ty; |
| 431 | let assert_properties_impl = quote_spanned! {properties_field_ty.span()=> |
| 432 | struct _AssertIntoFileProperties where #properties_field_ty: ::std::convert::Into<::lofty::properties::FileProperties>; |
| 433 | }; |
| 434 | |
| 435 | let struct_name = &file.struct_info.name; |
| 436 | let ret = quote! { |
| 437 | #assert_properties_impl |
| 438 | impl ::lofty::prelude::AudioFile for #struct_name { |
| 439 | type Properties = #properties_field_ty; |
| 440 | |
| 441 | fn read_from<R>(reader: &mut R, parse_options: ::lofty::config::ParseOptions) -> ::lofty::error::Result<Self> |
| 442 | where |
| 443 | R: std::io::Read + std::io::Seek, |
| 444 | { |
| 445 | #read_fn(reader, parse_options) |
| 446 | } |
| 447 | |
| 448 | fn save_to<F>(&self, file: &mut F, write_options: ::lofty::config::WriteOptions) -> ::lofty::error::Result<()> |
| 449 | where |
| 450 | F: ::lofty::io::FileLike, |
| 451 | ::lofty::error::LoftyError: ::std::convert::From<<F as ::lofty::io::Truncate>::Error>, |
| 452 | ::lofty::error::LoftyError: ::std::convert::From<<F as ::lofty::io::Length>::Error>, |
| 453 | { |
| 454 | use ::lofty::tag::TagExt as _; |
| 455 | use ::std::io::Seek as _; |
| 456 | #save_to_body |
| 457 | } |
| 458 | |
| 459 | fn properties(&self) -> &Self::Properties { |
| 460 | &self.properties |
| 461 | } |
| 462 | |
| 463 | #[allow(unreachable_code)] |
| 464 | fn contains_tag(&self) -> bool { |
| 465 | #( #tag_exists )||* |
| 466 | } |
| 467 | |
| 468 | #[allow(unreachable_code, unused_variables)] |
| 469 | fn contains_tag_type(&self, tag_type: ::lofty::tag::TagType) -> bool { |
| 470 | match tag_type { |
| 471 | #( ::lofty::tag::TagType::#tag_type => { #tag_exists_2 } ),* |
| 472 | _ => false |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | }; |
| 477 | |
| 478 | Ok(ret) |
| 479 | } |
| 480 | |
| 481 | fn get_save_to_body( |
| 482 | write_fn: Option<&proc_macro2::TokenStream>, |
| 483 | tag_fields: &[FieldContents], |
| 484 | ) -> proc_macro2::TokenStream { |
| 485 | // Custom write fn |
| 486 | if let Some(write_fn) = write_fn { |
| 487 | return quote! { |
| 488 | #write_fn(&self, file, write_options) |
| 489 | }; |
| 490 | } |
| 491 | |
| 492 | let tag_field_save = tag_fields.iter().map(|f| { |
| 493 | let name = &f.name; |
| 494 | if f.needs_option { |
| 495 | quote! { |
| 496 | if let Some(ref tag) = self.#name { |
| 497 | file.rewind()?; |
| 498 | tag.save_to(file, write_options)?; |
| 499 | } |
| 500 | } |
| 501 | } else { |
| 502 | quote! { |
| 503 | file.rewind()?; |
| 504 | self.#name.save_to(file, write_options)?; |
| 505 | } |
| 506 | } |
| 507 | }); |
| 508 | quote! { |
| 509 | #(#tag_field_save)* |
| 510 | Ok(()) |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | fn generate_from_taggedfile_impl(file: &LoftyFile) -> proc_macro2::TokenStream { |
| 515 | let tag_fields = &file.struct_info.fields.tags; |
| 516 | let conditions = tag_fields.iter().map(|f| { |
| 517 | let name = &f.name; |
| 518 | if f.needs_option { |
| 519 | quote! { |
| 520 | if let Some(t) = input.#name { |
| 521 | tags.push(t.into()); |
| 522 | } |
| 523 | } |
| 524 | } else { |
| 525 | quote! { tags.push(input.#name.into()); } |
| 526 | } |
| 527 | }); |
| 528 | |
| 529 | let file_type = &file.file_type; |
| 530 | let file_type_variant = if file.internal_details.has_internal_file_type { |
| 531 | quote! { ::lofty::file::FileType::#file_type } |
| 532 | } else { |
| 533 | let file_ty_str = file_type.to_string(); |
| 534 | quote! { ::lofty::file::FileType::Custom(#file_ty_str) } |
| 535 | }; |
| 536 | |
| 537 | let struct_name = &file.struct_info.name; |
| 538 | quote! { |
| 539 | impl ::std::convert::From<#struct_name> for ::lofty::file::TaggedFile { |
| 540 | fn from(input: #struct_name) -> Self { |
| 541 | use ::lofty::prelude::TaggedFileExt as _; |
| 542 | |
| 543 | ::lofty::file::TaggedFile::new( |
| 544 | #file_type_variant, |
| 545 | ::lofty::properties::FileProperties::from(input.properties), |
| 546 | { |
| 547 | let mut tags: Vec<::lofty::tag::Tag> = Vec::new(); |
| 548 | #( #conditions )* |
| 549 | |
| 550 | tags |
| 551 | } |
| 552 | ) |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | } |