| 1 |
// Cleanup when workspace lints can be overridden |
| 2 |
// https://github.com/rust-lang/cargo/issues/13157 |
| 3 |
#![forbid(unsafe_code)] |
| 4 |
#![warn(missing_copy_implementations, missing_debug_implementations)] |
| 5 |
#![doc(test(attr( |
| 6 |
// Problematic handling for foreign From<T> impls in tests |
| 7 |
// https://github.com/rust-lang/rust/issues/121621 |
| 8 |
allow(unknown_lints, non_local_definitions), |
| 9 |
deny( |
| 10 |
missing_debug_implementations, |
| 11 |
rust_2018_idioms, |
| 12 |
trivial_casts, |
| 13 |
trivial_numeric_casts, |
| 14 |
unused_extern_crates, |
| 15 |
unused_import_braces, |
| 16 |
unused_qualifications, |
| 17 |
warnings, |
| 18 |
), |
| 19 |
forbid(unsafe_code), |
| 20 |
)))] |
| 21 |
// Not needed for 2018 edition and conflicts with `rust_2018_idioms` |
| 22 |
#![doc(test(no_crate_inject))] |
| 23 |
#![doc(html_root_url = "https://docs.rs/serde_with_macros/3.12.0/")] |
| 24 |
// Tarpaulin does not work well with proc macros and marks most of the lines as uncovered. |
| 25 |
#![cfg(not(tarpaulin_include))] |
| 26 |
|
| 27 |
//! proc-macro extensions for [`serde_with`]. |
| 28 |
//! |
| 29 |
//! This crate should **NEVER** be used alone. |
| 30 |
//! All macros **MUST** be used via the re-exports in the [`serde_with`] crate. |
| 31 |
//! |
| 32 |
//! [`serde_with`]: https://crates.io/crates/serde_with/ |
| 33 |
|
| 34 |
mod apply; |
| 35 |
mod lazy_bool; |
| 36 |
mod utils; |
| 37 |
|
| 38 |
use crate::utils::{ |
| 39 |
split_with_de_lifetime, DeriveOptions, IteratorExt as _, SchemaFieldCondition, |
| 40 |
SchemaFieldConfig, |
| 41 |
}; |
| 42 |
use darling::{ |
| 43 |
ast::NestedMeta, |
| 44 |
util::{Flag, Override}, |
| 45 |
Error as DarlingError, FromField, FromMeta, |
| 46 |
}; |
| 47 |
use proc_macro::TokenStream; |
| 48 |
use proc_macro2::{Span, TokenStream as TokenStream2}; |
| 49 |
use quote::quote; |
| 50 |
use syn::{ |
| 51 |
parse::Parser, |
| 52 |
parse_macro_input, parse_quote, |
| 53 |
punctuated::{Pair, Punctuated}, |
| 54 |
spanned::Spanned, |
| 55 |
DeriveInput, Error, Field, Fields, GenericArgument, ItemEnum, ItemStruct, Meta, Path, |
| 56 |
PathArguments, ReturnType, Token, Type, |
| 57 |
}; |
| 58 |
|
| 59 |
/// Apply function on every field of structs or enums |
| 60 |
fn apply_function_to_struct_and_enum_fields<F>( |
| 61 |
input: TokenStream, |
| 62 |
function: F, |
| 63 |
) -> Result<TokenStream2, Error> |
| 64 |
where |
| 65 |
F: Copy, |
| 66 |
F: Fn(&mut Field) -> Result<(), String>, |
| 67 |
{ |
| 68 |
/// Handle a single struct or a single enum variant |
| 69 |
fn apply_on_fields<F>(fields: &mut Fields, function: F) -> Result<(), Error> |
| 70 |
where |
| 71 |
F: Fn(&mut Field) -> Result<(), String>, |
| 72 |
{ |
| 73 |
match fields { |
| 74 |
// simple, no fields, do nothing |
| 75 |
Fields::Unit => Ok(()), |
| 76 |
Fields::Named(ref mut fields) => fields |
| 77 |
.named |
| 78 |
.iter_mut() |
| 79 |
.map(|field| function(field).map_err(|err| Error::new(field.span(), err))) |
| 80 |
.collect_error(), |
| 81 |
Fields::Unnamed(ref mut fields) => fields |
| 82 |
.unnamed |
| 83 |
.iter_mut() |
| 84 |
.map(|field| function(field).map_err(|err| Error::new(field.span(), err))) |
| 85 |
.collect_error(), |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
// For each field in the struct given by `input`, add the `skip_serializing_if` attribute, |
| 90 |
// if and only if, it is of type `Option` |
| 91 |
if let Ok(mut input) = syn::parse::<ItemStruct>(input.clone()) { |
| 92 |
apply_on_fields(&mut input.fields, function)?; |
| 93 |
Ok(quote!(#input)) |
| 94 |
} else if let Ok(mut input) = syn::parse::<ItemEnum>(input) { |
| 95 |
input |
| 96 |
.variants |
| 97 |
.iter_mut() |
| 98 |
.map(|variant| apply_on_fields(&mut variant.fields, function)) |
| 99 |
.collect_error()?; |
| 100 |
Ok(quote!(#input)) |
| 101 |
} else { |
| 102 |
Err(Error::new( |
| 103 |
Span::call_site(), |
| 104 |
"The attribute can only be applied to struct or enum definitions.", |
| 105 |
)) |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
/// Like [`apply_function_to_struct_and_enum_fields`] but for darling errors |
| 110 |
fn apply_function_to_struct_and_enum_fields_darling<F>( |
| 111 |
input: TokenStream, |
| 112 |
serde_with_crate_path: &Path, |
| 113 |
function: F, |
| 114 |
) -> Result<TokenStream2, DarlingError> |
| 115 |
where |
| 116 |
F: Copy, |
| 117 |
F: Fn(&mut Field) -> Result<(), DarlingError>, |
| 118 |
{ |
| 119 |
/// Handle a single struct or a single enum variant |
| 120 |
fn apply_on_fields<F>(fields: &mut Fields, function: F) -> Result<(), DarlingError> |
| 121 |
where |
| 122 |
F: Fn(&mut Field) -> Result<(), DarlingError>, |
| 123 |
{ |
| 124 |
match fields { |
| 125 |
// simple, no fields, do nothing |
| 126 |
Fields::Unit => Ok(()), |
| 127 |
Fields::Named(ref mut fields) => { |
| 128 |
let errors: Vec<DarlingError> = fields |
| 129 |
.named |
| 130 |
.iter_mut() |
| 131 |
.map(|field| function(field).map_err(|err| err.with_span(&field))) |
| 132 |
// turn the Err variant into the Some, such that we only collect errors |
| 133 |
.filter_map(|res| match res { |
| 134 |
Err(e) => Some(e), |
| 135 |
Ok(()) => None, |
| 136 |
}) |
| 137 |
.collect(); |
| 138 |
if errors.is_empty() { |
| 139 |
Ok(()) |
| 140 |
} else { |
| 141 |
Err(DarlingError::multiple(errors)) |
| 142 |
} |
| 143 |
} |
| 144 |
Fields::Unnamed(ref mut fields) => { |
| 145 |
let errors: Vec<DarlingError> = fields |
| 146 |
.unnamed |
| 147 |
.iter_mut() |
| 148 |
.map(|field| function(field).map_err(|err| err.with_span(&field))) |
| 149 |
// turn the Err variant into the Some, such that we only collect errors |
| 150 |
.filter_map(|res| match res { |
| 151 |
Err(e) => Some(e), |
| 152 |
Ok(()) => None, |
| 153 |
}) |
| 154 |
.collect(); |
| 155 |
if errors.is_empty() { |
| 156 |
Ok(()) |
| 157 |
} else { |
| 158 |
Err(DarlingError::multiple(errors)) |
| 159 |
} |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// Add a dummy derive macro which consumes (makes inert) all field attributes |
| 165 |
let consume_serde_as_attribute = parse_quote!( |
| 166 |
#[derive(#serde_with_crate_path::__private_consume_serde_as_attributes)] |
| 167 |
); |
| 168 |
|
| 169 |
// For each field in the struct given by `input`, add the `skip_serializing_if` attribute, |
| 170 |
// if and only if, it is of type `Option` |
| 171 |
if let Ok(mut input) = syn::parse::<ItemStruct>(input.clone()) { |
| 172 |
apply_on_fields(&mut input.fields, function)?; |
| 173 |
input.attrs.push(consume_serde_as_attribute); |
| 174 |
Ok(quote!(#input)) |
| 175 |
} else if let Ok(mut input) = syn::parse::<ItemEnum>(input) { |
| 176 |
// Prevent serde_as on enum variants |
| 177 |
let mut errors: Vec<DarlingError> = input |
| 178 |
.variants |
| 179 |
.iter() |
| 180 |
.flat_map(|variant| { |
| 181 |
variant.attrs.iter().filter_map(|attr| { |
| 182 |
if attr.path().is_ident("serde_as") { |
| 183 |
Some( |
| 184 |
DarlingError::custom( |
| 185 |
"serde_as attribute is not allowed on enum variants", |
| 186 |
) |
| 187 |
.with_span(&attr), |
| 188 |
) |
| 189 |
} else { |
| 190 |
None |
| 191 |
} |
| 192 |
}) |
| 193 |
}) |
| 194 |
.collect(); |
| 195 |
// Process serde_as on all fields |
| 196 |
errors.extend( |
| 197 |
input |
| 198 |
.variants |
| 199 |
.iter_mut() |
| 200 |
.map(|variant| apply_on_fields(&mut variant.fields, function)) |
| 201 |
// turn the Err variant into the Some, such that we only collect errors |
| 202 |
.filter_map(|res| match res { |
| 203 |
Err(e) => Some(e), |
| 204 |
Ok(()) => None, |
| 205 |
}), |
| 206 |
); |
| 207 |
|
| 208 |
if errors.is_empty() { |
| 209 |
input.attrs.push(consume_serde_as_attribute); |
| 210 |
Ok(quote!(#input)) |
| 211 |
} else { |
| 212 |
Err(DarlingError::multiple(errors)) |
| 213 |
} |
| 214 |
} else { |
| 215 |
Err(DarlingError::custom( |
| 216 |
"The attribute can only be applied to struct or enum definitions.", |
| 217 |
) |
| 218 |
.with_span(&Span::call_site())) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
/// Add `skip_serializing_if` annotations to [`Option`] fields. |
| 223 |
/// |
| 224 |
/// The attribute can be added to structs and enums. |
| 225 |
/// The `#[skip_serializing_none]` attribute must be placed *before* the `#[derive]` attribute. |
| 226 |
/// |
| 227 |
/// # Example |
| 228 |
/// |
| 229 |
/// JSON APIs sometimes have many optional values. |
| 230 |
/// Missing values should not be serialized, to keep the serialized format smaller. |
| 231 |
/// Such a data type might look like: |
| 232 |
/// |
| 233 |
/// ```rust |
| 234 |
/// # use serde::Serialize; |
| 235 |
/// # |
| 236 |
/// # #[allow(dead_code)] |
| 237 |
/// #[derive(Serialize)] |
| 238 |
/// struct Data { |
| 239 |
/// #[serde(skip_serializing_if = "Option::is_none")] |
| 240 |
/// a: Option<String>, |
| 241 |
/// #[serde(skip_serializing_if = "Option::is_none")] |
| 242 |
/// b: Option<u64>, |
| 243 |
/// #[serde(skip_serializing_if = "Option::is_none")] |
| 244 |
/// c: Option<String>, |
| 245 |
/// #[serde(skip_serializing_if = "Option::is_none")] |
| 246 |
/// d: Option<bool>, |
| 247 |
/// } |
| 248 |
/// ``` |
| 249 |
/// |
| 250 |
/// The `skip_serializing_if` annotation is repetitive and harms readability. |
| 251 |
/// Instead, the same struct can be written as: |
| 252 |
/// |
| 253 |
/// ```rust |
| 254 |
/// # use serde::Serialize; |
| 255 |
/// # use serde_with_macros::skip_serializing_none; |
| 256 |
/// # |
| 257 |
/// # #[allow(dead_code)] |
| 258 |
/// #[skip_serializing_none] |
| 259 |
/// #[derive(Serialize)] |
| 260 |
/// struct Data { |
| 261 |
/// a: Option<String>, |
| 262 |
/// b: Option<u64>, |
| 263 |
/// c: Option<String>, |
| 264 |
/// // Always serialize field d even if None |
| 265 |
/// #[serialize_always] |
| 266 |
/// d: Option<bool>, |
| 267 |
/// } |
| 268 |
/// ``` |
| 269 |
/// |
| 270 |
/// Existing `skip_serializing_if` annotations will not be altered. |
| 271 |
/// |
| 272 |
/// If some values should always be serialized, then `serialize_always` can be used. |
| 273 |
/// |
| 274 |
/// # Limitations |
| 275 |
/// |
| 276 |
/// The `serialize_always` cannot be used together with a manual `skip_serializing_if` annotations, |
| 277 |
/// as these conflict in their meaning. A compile error will be generated if this occurs. |
| 278 |
/// |
| 279 |
/// The `skip_serializing_none` only works if the type is called `Option`, |
| 280 |
/// `std::option::Option`, or `core::option::Option`. Type aliasing an [`Option`] and giving it |
| 281 |
/// another name, will cause this field to be ignored. This cannot be supported, as proc-macros run |
| 282 |
/// before type checking, thus it is not possible to determine if a type alias refers to an |
| 283 |
/// [`Option`]. |
| 284 |
/// |
| 285 |
/// ```rust |
| 286 |
/// # use serde::Serialize; |
| 287 |
/// # use serde_with_macros::skip_serializing_none; |
| 288 |
/// # #[allow(dead_code)] |
| 289 |
/// type MyOption<T> = Option<T>; |
| 290 |
/// |
| 291 |
/// # #[allow(dead_code)] |
| 292 |
/// #[skip_serializing_none] |
| 293 |
/// #[derive(Serialize)] |
| 294 |
/// struct Data { |
| 295 |
/// a: MyOption<String>, // This field will not be skipped |
| 296 |
/// } |
| 297 |
/// ``` |
| 298 |
/// |
| 299 |
/// Likewise, if you import a type and name it `Option`, the `skip_serializing_if` attributes will |
| 300 |
/// be added and compile errors will occur, if `Option::is_none` is not a valid function. |
| 301 |
/// Here the function `Vec::is_none` does not exist, and therefore the example fails to compile. |
| 302 |
/// |
| 303 |
/// ```rust,compile_fail |
| 304 |
/// # use serde::Serialize; |
| 305 |
/// # use serde_with_macros::skip_serializing_none; |
| 306 |
/// use std::vec::Vec as Option; |
| 307 |
/// |
| 308 |
/// #[skip_serializing_none] |
| 309 |
/// #[derive(Serialize)] |
| 310 |
/// struct Data { |
| 311 |
/// a: Option<String>, |
| 312 |
/// } |
| 313 |
/// ``` |
| 314 |
#[proc_macro_attribute] |
| 315 |
pub fn skip_serializing_none(_args: TokenStream, input: TokenStream) -> TokenStream { |
| 316 |
let res = |
| 317 |
apply_function_to_struct_and_enum_fields(input, skip_serializing_none_add_attr_to_field) |
| 318 |
.unwrap_or_else(|err| err.to_compile_error()); |
| 319 |
TokenStream::from(res) |
| 320 |
} |
| 321 |
|
| 322 |
/// Add the `skip_serializing_if` annotation to each field of the struct |
| 323 |
fn skip_serializing_none_add_attr_to_field(field: &mut Field) -> Result<(), String> { |
| 324 |
if is_std_option(&field.ty) { |
| 325 |
let has_skip_serializing_if = field_has_attribute(field, "serde", "skip_serializing_if"); |
| 326 |
|
| 327 |
// Remove the `serialize_always` attribute |
| 328 |
let mut has_always_attr = false; |
| 329 |
field.attrs.retain(|attr| { |
| 330 |
let has_attr = attr.path().is_ident("serialize_always"); |
| 331 |
has_always_attr |= has_attr; |
| 332 |
!has_attr |
| 333 |
}); |
| 334 |
|
| 335 |
// Error on conflicting attributes |
| 336 |
if has_always_attr && has_skip_serializing_if { |
| 337 |
let mut msg = r#"The attributes `serialize_always` and `serde(skip_serializing_if = "...")` cannot be used on the same field"#.to_string(); |
| 338 |
if let Some(ident) = &field.ident { |
| 339 |
msg += ": `"; |
| 340 |
msg += &ident.to_string(); |
| 341 |
msg += "`"; |
| 342 |
} |
| 343 |
msg += "."; |
| 344 |
return Err(msg); |
| 345 |
} |
| 346 |
|
| 347 |
// Do nothing if `skip_serializing_if` or `serialize_always` is already present |
| 348 |
if has_skip_serializing_if || has_always_attr { |
| 349 |
return Ok(()); |
| 350 |
} |
| 351 |
|
| 352 |
// Add the `skip_serializing_if` attribute |
| 353 |
let attr = parse_quote!( |
| 354 |
#[serde(skip_serializing_if = "Option::is_none")] |
| 355 |
); |
| 356 |
field.attrs.push(attr); |
| 357 |
} else { |
| 358 |
// Warn on use of `serialize_always` on non-Option fields |
| 359 |
let has_attr = field |
| 360 |
.attrs |
| 361 |
.iter() |
| 362 |
.any(|attr| attr.path().is_ident("serialize_always")); |
| 363 |
if has_attr { |
| 364 |
return Err("`serialize_always` may only be used on fields of type `Option`.".into()); |
| 365 |
} |
| 366 |
} |
| 367 |
Ok(()) |
| 368 |
} |
| 369 |
|
| 370 |
/// Return `true`, if the type path refers to `std::option::Option` |
| 371 |
/// |
| 372 |
/// Accepts |
| 373 |
/// |
| 374 |
/// * `Option` |
| 375 |
/// * `std::option::Option`, with or without leading `::` |
| 376 |
/// * `core::option::Option`, with or without leading `::` |
| 377 |
fn is_std_option(type_: &Type) -> bool { |
| 378 |
match type_ { |
| 379 |
Type::Array(_) |
| 380 |
| Type::BareFn(_) |
| 381 |
| Type::ImplTrait(_) |
| 382 |
| Type::Infer(_) |
| 383 |
| Type::Macro(_) |
| 384 |
| Type::Never(_) |
| 385 |
| Type::Ptr(_) |
| 386 |
| Type::Reference(_) |
| 387 |
| Type::Slice(_) |
| 388 |
| Type::TraitObject(_) |
| 389 |
| Type::Tuple(_) |
| 390 |
| Type::Verbatim(_) => false, |
| 391 |
|
| 392 |
Type::Group(syn::TypeGroup { elem, .. }) |
| 393 |
| Type::Paren(syn::TypeParen { elem, .. }) |
| 394 |
| Type::Path(syn::TypePath { |
| 395 |
qself: Some(syn::QSelf { ty: elem, .. }), |
| 396 |
.. |
| 397 |
}) => is_std_option(elem), |
| 398 |
|
| 399 |
Type::Path(syn::TypePath { qself: None, path }) => { |
| 400 |
(path.leading_colon.is_none() |
| 401 |
&& path.segments.len() == 1 |
| 402 |
&& path.segments[0].ident == "Option") |
| 403 |
|| (path.segments.len() == 3 |
| 404 |
&& (path.segments[0].ident == "std" || path.segments[0].ident == "core") |
| 405 |
&& path.segments[1].ident == "option" |
| 406 |
&& path.segments[2].ident == "Option") |
| 407 |
} |
| 408 |
_ => false, |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
/// Determine if the `field` has an attribute with given `namespace` and `name` |
| 413 |
/// |
| 414 |
/// On the example of |
| 415 |
/// `#[serde(skip_serializing_if = "Option::is_none")]` |
| 416 |
/// |
| 417 |
/// * `serde` is the outermost path, here namespace |
| 418 |
/// * it contains a `Meta::List` |
| 419 |
/// * which contains in another Meta a `Meta::NameValue` |
| 420 |
/// * with the name being `skip_serializing_if` |
| 421 |
fn field_has_attribute(field: &Field, namespace: &str, name: &str) -> bool { |
| 422 |
for attr in &field.attrs { |
| 423 |
if attr.path().is_ident(namespace) { |
| 424 |
// Ignore non parsable attributes, as these are not important for us |
| 425 |
if let Meta::List(expr) = &attr.meta { |
| 426 |
let nested = match Punctuated::<Meta, Token![,]>::parse_terminated |
| 427 |
.parse2(expr.tokens.clone()) |
| 428 |
{ |
| 429 |
Ok(nested) => nested, |
| 430 |
Err(_) => continue, |
| 431 |
}; |
| 432 |
for expr in nested { |
| 433 |
match expr { |
| 434 |
Meta::NameValue(expr) => { |
| 435 |
if let Some(ident) = expr.path.get_ident() { |
| 436 |
if *ident == name { |
| 437 |
return true; |
| 438 |
} |
| 439 |
} |
| 440 |
} |
| 441 |
Meta::Path(expr) => { |
| 442 |
if let Some(ident) = expr.get_ident() { |
| 443 |
if *ident == name { |
| 444 |
return true; |
| 445 |
} |
| 446 |
} |
| 447 |
} |
| 448 |
_ => (), |
| 449 |
} |
| 450 |
} |
| 451 |
} |
| 452 |
} |
| 453 |
} |
| 454 |
false |
| 455 |
} |
| 456 |
|
| 457 |
/// Convenience macro to use the [`serde_as`] system. |
| 458 |
/// |
| 459 |
/// The [`serde_as`] system is designed as a more flexible alternative to serde's `with` annotation. |
| 460 |
/// The `#[serde_as]` attribute must be placed *before* the `#[derive]` attribute. |
| 461 |
/// Each field of a struct or enum can be annotated with `#[serde_as(...)]` to specify which |
| 462 |
/// transformations should be applied. `serde_as` is *not* supported on enum variants. |
| 463 |
/// This is in contrast to `#[serde(with = "...")]`. |
| 464 |
/// |
| 465 |
/// # Example |
| 466 |
/// |
| 467 |
/// ```rust,ignore |
| 468 |
/// use serde_with::{serde_as, DisplayFromStr, Map}; |
| 469 |
/// |
| 470 |
/// #[serde_as] |
| 471 |
/// #[derive(Serialize, Deserialize)] |
| 472 |
/// struct Data { |
| 473 |
/// /// Serialize into number |
| 474 |
/// #[serde_as(as = "_")] |
| 475 |
/// a: u32, |
| 476 |
/// |
| 477 |
/// /// Serialize into String |
| 478 |
/// #[serde_as(as = "DisplayFromStr")] |
| 479 |
/// b: u32, |
| 480 |
/// |
| 481 |
/// /// Serialize into a map from String to String |
| 482 |
/// #[serde_as(as = "Map<DisplayFromStr, _>")] |
| 483 |
/// c: Vec<(u32, String)>, |
| 484 |
/// } |
| 485 |
/// ``` |
| 486 |
/// |
| 487 |
/// # Alternative path to `serde_with` crate |
| 488 |
/// |
| 489 |
/// If `serde_with` is not available at the default path, its path should be specified with the |
| 490 |
/// `crate` argument. See [re-exporting `serde_as`] for more use case information. |
| 491 |
/// |
| 492 |
/// ```rust,ignore |
| 493 |
/// #[serde_as(crate = "::some_other_lib::serde_with")] |
| 494 |
/// #[derive(Deserialize)] |
| 495 |
/// struct Data { |
| 496 |
/// #[serde_as(as = "_")] |
| 497 |
/// a: u32, |
| 498 |
/// } |
| 499 |
/// ``` |
| 500 |
/// |
| 501 |
/// # What this macro does |
| 502 |
/// |
| 503 |
/// The `serde_as` macro only serves a convenience function. |
| 504 |
/// All the steps it performs, can easily be done manually, in case the cost of an attribute macro |
| 505 |
/// is deemed too high. The functionality can best be described with an example. |
| 506 |
/// |
| 507 |
/// ```rust,ignore |
| 508 |
/// #[serde_as] |
| 509 |
/// #[derive(serde::Serialize)] |
| 510 |
/// struct Foo { |
| 511 |
/// #[serde_as(as = "Vec<_>")] |
| 512 |
/// bar: Vec<u32>, |
| 513 |
/// |
| 514 |
/// #[serde_as(as = "Option<DisplayFromStr>")] |
| 515 |
/// baz: Option<u32>, |
| 516 |
/// } |
| 517 |
/// ``` |
| 518 |
/// |
| 519 |
/// 1. All the placeholder type `_` will be replaced with `::serde_with::Same`. |
| 520 |
/// The placeholder type `_` marks all the places where the type's `Serialize` implementation |
| 521 |
/// should be used. In the example, it means that the `u32` values will serialize with the |
| 522 |
/// `Serialize` implementation of `u32`. The `Same` type implements `SerializeAs` whenever the |
| 523 |
/// underlying type implements `Serialize` and is used to make the two traits compatible. |
| 524 |
/// |
| 525 |
/// If you specify a custom path for `serde_with` via the `crate` attribute, the path to the |
| 526 |
/// `Same` type will be altered accordingly. |
| 527 |
/// |
| 528 |
/// 2. Wrap the type from the annotation inside a `::serde_with::As`. |
| 529 |
/// In the above example we now have something like `::serde_with::As::<Vec<::serde_with::Same>>`. |
| 530 |
/// The `As` type acts as the opposite of the `Same` type. |
| 531 |
/// It allows using a `SerializeAs` type whenever a `Serialize` is required. |
| 532 |
/// |
| 533 |
/// 3. Translate the `*as` attributes into the serde equivalent ones. |
| 534 |
/// `#[serde_as(as = ...)]` will become `#[serde(with = ...)]`. |
| 535 |
/// Similarly, `serialize_as` is translated to `serialize_with`. |
| 536 |
/// |
| 537 |
/// The field attributes will be kept on the struct/enum such that other macros can use them |
| 538 |
/// too. |
| 539 |
/// |
| 540 |
/// 4. It searches `#[serde_as(as = ...)]` if there is a type named `BorrowCow` under any path. |
| 541 |
/// If `BorrowCow` is found, the attribute `#[serde(borrow)]` is added to the field. |
| 542 |
/// If `#[serde(borrow)]` or `#[serde(borrow = "...")]` is already present, this step will be |
| 543 |
/// skipped. |
| 544 |
/// |
| 545 |
/// 5. Restore the ability of accepting missing fields if both the field and the transformation are `Option`. |
| 546 |
/// |
| 547 |
/// An `Option` is detected by an exact text match. |
| 548 |
/// Renaming an import or type aliases can cause confusion here. |
| 549 |
/// The following variants are supported. |
| 550 |
/// * `Option` |
| 551 |
/// * `std::option::Option`, with or without leading `::` |
| 552 |
/// * `core::option::Option`, with or without leading `::` |
| 553 |
/// |
| 554 |
/// If the field is of type `Option<T>` and the attribute `#[serde_as(as = "Option<S>")]` (also |
| 555 |
/// `deserialize_as`; for any `T`/`S`) then `#[serde(default)]` is applied to the field. |
| 556 |
/// |
| 557 |
/// This restores the ability of accepting missing fields, which otherwise often leads to confusing [serde_with#185](https://github.com/jonasbb/serde_with/issues/185). |
| 558 |
/// `#[serde(default)]` is not applied, if it already exists. |
| 559 |
/// It only triggers if both field and transformation are `Option`s. |
| 560 |
/// For example, using `#[serde_as(as = "NoneAsEmptyString")]` on `Option<String>` will not see |
| 561 |
/// any change. |
| 562 |
/// |
| 563 |
/// If the automatically applied attribute is undesired, the behavior can be suppressed by adding |
| 564 |
/// `#[serde_as(no_default)]`. |
| 565 |
/// |
| 566 |
/// This can be combined like `#[serde_as(as = "Option<S>", no_default)]`. |
| 567 |
/// |
| 568 |
/// After all these steps, the code snippet will have transformed into roughly this. |
| 569 |
/// |
| 570 |
/// ```rust,ignore |
| 571 |
/// #[derive(serde::Serialize)] |
| 572 |
/// struct Foo { |
| 573 |
/// #[serde_as(as = "Vec<_>")] |
| 574 |
/// #[serde(with = "::serde_with::As::<Vec<::serde_with::Same>>")] |
| 575 |
/// bar: Vec<u32>, |
| 576 |
/// |
| 577 |
/// #[serde_as(as = "Option<DisplayFromStr>")] |
| 578 |
/// #[serde(default)] |
| 579 |
/// #[serde(with = "::serde_with::As::<Option<DisplayFromStr>>")] |
| 580 |
/// baz: Option<u32>, |
| 581 |
/// } |
| 582 |
/// ``` |
| 583 |
/// |
| 584 |
/// # A note on `schemars` integration |
| 585 |
/// When the `schemars_0_8` feature is enabled this macro will scan for |
| 586 |
/// `#[derive(JsonSchema)]` attributes and, if found, will add |
| 587 |
/// `#[schemars(with = "Schema<T, ...>")]` annotations to any fields with a |
| 588 |
/// `#[serde_as(as = ...)]` annotation. If you wish to override the default |
| 589 |
/// behavior here you can add `#[serde_as(schemars = true)]` or |
| 590 |
/// `#[serde_as(schemars = false)]`. |
| 591 |
/// |
| 592 |
/// Note that this macro will check for any of the following derive paths: |
| 593 |
/// * `JsonSchema` |
| 594 |
/// * `schemars::JsonSchema` |
| 595 |
/// * `::schemars::JsonSchema` |
| 596 |
/// |
| 597 |
/// It will also work if the relevant derive is behind a `#[cfg_attr]` attribute |
| 598 |
/// and propagate the `#[cfg_attr]` to the various `#[schemars]` field attributes. |
| 599 |
/// |
| 600 |
/// [`serde_as`]: https://docs.rs/serde_with/3.12.0/serde_with/guide/index.html |
| 601 |
/// [re-exporting `serde_as`]: https://docs.rs/serde_with/3.12.0/serde_with/guide/serde_as/index.html#re-exporting-serde_as |
| 602 |
#[proc_macro_attribute] |
| 603 |
pub fn serde_as(args: TokenStream, input: TokenStream) -> TokenStream { |
| 604 |
#[derive(FromMeta)] |
| 605 |
struct SerdeContainerOptions { |
| 606 |
#[darling(rename = "crate")] |
| 607 |
alt_crate_path: Option<Path>, |
| 608 |
#[darling(rename = "schemars")] |
| 609 |
enable_schemars_support: Option<bool>, |
| 610 |
} |
| 611 |
|
| 612 |
match NestedMeta::parse_meta_list(args.into()) { |
| 613 |
Ok(list) => { |
| 614 |
let container_options = match SerdeContainerOptions::from_list(&list) { |
| 615 |
Ok(v) => v, |
| 616 |
Err(e) => { |
| 617 |
return TokenStream::from(e.write_errors()); |
| 618 |
} |
| 619 |
}; |
| 620 |
|
| 621 |
let serde_with_crate_path = container_options |
| 622 |
.alt_crate_path |
| 623 |
.unwrap_or_else(|| syn::parse_quote!(::serde_with)); |
| 624 |
|
| 625 |
let schemars_config = match container_options.enable_schemars_support { |
| 626 |
_ if cfg!(not(feature = "schemars_0_8")) => SchemaFieldConfig::False, |
| 627 |
Some(condition) => condition.into(), |
| 628 |
None => utils::has_derive_jsonschema(input.clone()).unwrap_or_default(), |
| 629 |
}; |
| 630 |
|
| 631 |
// Convert any error message into a nice compiler error |
| 632 |
let res = apply_function_to_struct_and_enum_fields_darling( |
| 633 |
input, |
| 634 |
&serde_with_crate_path, |
| 635 |
|field| serde_as_add_attr_to_field(field, &serde_with_crate_path, &schemars_config), |
| 636 |
) |
| 637 |
.unwrap_or_else(darling::Error::write_errors); |
| 638 |
TokenStream::from(res) |
| 639 |
} |
| 640 |
Err(e) => TokenStream::from(DarlingError::from(e).write_errors()), |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
/// Inspect the field and convert the `serde_as` attribute into the classical `serde` |
| 645 |
fn serde_as_add_attr_to_field( |
| 646 |
field: &mut Field, |
| 647 |
serde_with_crate_path: &Path, |
| 648 |
schemars_config: &SchemaFieldConfig, |
| 649 |
) -> Result<(), DarlingError> { |
| 650 |
#[derive(FromField)] |
| 651 |
#[darling(attributes(serde_as))] |
| 652 |
struct SerdeAsOptions { |
| 653 |
/// The original type of the field |
| 654 |
ty: Type, |
| 655 |
|
| 656 |
r#as: Option<Type>, |
| 657 |
deserialize_as: Option<Type>, |
| 658 |
serialize_as: Option<Type>, |
| 659 |
no_default: Flag, |
| 660 |
} |
| 661 |
|
| 662 |
impl SerdeAsOptions { |
| 663 |
fn has_any_set(&self) -> bool { |
| 664 |
self.r#as.is_some() || self.deserialize_as.is_some() || self.serialize_as.is_some() |
| 665 |
} |
| 666 |
} |
| 667 |
|
| 668 |
#[derive(FromField)] |
| 669 |
#[darling(attributes(serde), allow_unknown_fields)] |
| 670 |
struct SerdeOptions { |
| 671 |
with: Option<String>, |
| 672 |
deserialize_with: Option<String>, |
| 673 |
serialize_with: Option<String>, |
| 674 |
|
| 675 |
borrow: Option<Override<String>>, |
| 676 |
default: Option<Override<String>>, |
| 677 |
} |
| 678 |
|
| 679 |
impl SerdeOptions { |
| 680 |
fn has_any_set(&self) -> bool { |
| 681 |
self.with.is_some() || self.deserialize_with.is_some() || self.serialize_with.is_some() |
| 682 |
} |
| 683 |
} |
| 684 |
|
| 685 |
/// Emit a `borrow` annotation, if the replacement type requires borrowing. |
| 686 |
fn emit_borrow_annotation(serde_options: &SerdeOptions, as_type: &Type, field: &mut Field) { |
| 687 |
let type_borrowcow = &syn::parse_quote!(BorrowCow); |
| 688 |
// If the field is not borrowed yet, check if we need to borrow it. |
| 689 |
if serde_options.borrow.is_none() && has_type_embedded(as_type, type_borrowcow) { |
| 690 |
let attr_borrow = parse_quote!(#[serde(borrow)]); |
| 691 |
field.attrs.push(attr_borrow); |
| 692 |
} |
| 693 |
} |
| 694 |
|
| 695 |
/// Emit a `default` annotation, if `as_type` and `field` are both `Option`. |
| 696 |
fn emit_default_annotation( |
| 697 |
serde_as_options: &SerdeAsOptions, |
| 698 |
serde_options: &SerdeOptions, |
| 699 |
as_type: &Type, |
| 700 |
field: &mut Field, |
| 701 |
) { |
| 702 |
if !serde_as_options.no_default.is_present() |
| 703 |
&& serde_options.default.is_none() |
| 704 |
&& is_std_option(as_type) |
| 705 |
&& is_std_option(&field.ty) |
| 706 |
{ |
| 707 |
let attr_borrow = parse_quote!(#[serde(default)]); |
| 708 |
field.attrs.push(attr_borrow); |
| 709 |
} |
| 710 |
} |
| 711 |
|
| 712 |
// syn v2 no longer supports keywords in the path position of an attribute. |
| 713 |
// That breaks #[serde_as(as = "FooBar")], since `as` is a keyword. |
| 714 |
// For each attribute, that is named `serde_as`, we replace the `as` keyword with `r#as`. |
| 715 |
let mut has_serde_as = false; |
| 716 |
field.attrs.iter_mut().for_each(|attr| { |
| 717 |
if attr.path().is_ident("serde_as") { |
| 718 |
// We found a `serde_as` attribute. |
| 719 |
// Remember that such that we can quick exit otherwise |
| 720 |
has_serde_as = true; |
| 721 |
|
| 722 |
if let Meta::List(metalist) = &mut attr.meta { |
| 723 |
metalist.tokens = std::mem::take(&mut metalist.tokens) |
| 724 |
.into_iter() |
| 725 |
.map(|token| { |
| 726 |
use proc_macro2::{Ident, TokenTree}; |
| 727 |
|
| 728 |
// Replace `as` with `r#as`. |
| 729 |
match token { |
| 730 |
TokenTree::Ident(ident) if ident == "as" => { |
| 731 |
TokenTree::Ident(Ident::new_raw("as", ident.span())) |
| 732 |
} |
| 733 |
_ => token, |
| 734 |
} |
| 735 |
}) |
| 736 |
.collect(); |
| 737 |
} |
| 738 |
} |
| 739 |
}); |
| 740 |
// If there is no `serde_as` attribute, we can exit early. |
| 741 |
if !has_serde_as { |
| 742 |
return Ok(()); |
| 743 |
} |
| 744 |
let serde_as_options = SerdeAsOptions::from_field(field)?; |
| 745 |
let serde_options = SerdeOptions::from_field(field)?; |
| 746 |
|
| 747 |
let mut errors = Vec::new(); |
| 748 |
if !serde_as_options.has_any_set() { |
| 749 |
errors.push(DarlingError::custom("An empty `serde_as` attribute on a field has no effect. You are missing an `as`, `serialize_as`, or `deserialize_as` parameter.")); |
| 750 |
} |
| 751 |
|
| 752 |
// Check if there are any conflicting attributes |
| 753 |
if serde_as_options.has_any_set() && serde_options.has_any_set() { |
| 754 |
errors.push(DarlingError::custom("Cannot combine `serde_as` with serde's `with`, `deserialize_with`, or `serialize_with`.")); |
| 755 |
} |
| 756 |
|
| 757 |
if serde_as_options.r#as.is_some() && serde_as_options.deserialize_as.is_some() { |
| 758 |
errors.push(DarlingError::custom("Cannot combine `as` with `deserialize_as`. Use `serialize_as` to specify different serialization code.")); |
| 759 |
} else if serde_as_options.r#as.is_some() && serde_as_options.serialize_as.is_some() { |
| 760 |
errors.push(DarlingError::custom("Cannot combine `as` with `serialize_as`. Use `deserialize_as` to specify different deserialization code.")); |
| 761 |
} |
| 762 |
|
| 763 |
if !errors.is_empty() { |
| 764 |
return Err(DarlingError::multiple(errors)); |
| 765 |
} |
| 766 |
|
| 767 |
let type_original = &serde_as_options.ty; |
| 768 |
let type_same = &syn::parse_quote!(#serde_with_crate_path::Same); |
| 769 |
if let Some(type_) = &serde_as_options.r#as { |
| 770 |
emit_borrow_annotation(&serde_options, type_, field); |
| 771 |
emit_default_annotation(&serde_as_options, &serde_options, type_, field); |
| 772 |
|
| 773 |
let replacement_type = replace_infer_type_with_type(type_.clone(), type_same); |
| 774 |
let attr_inner_tokens = quote!(#serde_with_crate_path::As::<#replacement_type>).to_string(); |
| 775 |
let attr = parse_quote!(#[serde(with = #attr_inner_tokens)]); |
| 776 |
field.attrs.push(attr); |
| 777 |
|
| 778 |
match schemars_config { |
| 779 |
SchemaFieldConfig::False => {} |
| 780 |
lhs => { |
| 781 |
let rhs = utils::schemars_with_attr_if( |
| 782 |
&field.attrs, |
| 783 |
&["with", "serialize_with", "deserialize_with", "schema_with"], |
| 784 |
)?; |
| 785 |
|
| 786 |
match lhs & !rhs { |
| 787 |
SchemaFieldConfig::False => {} |
| 788 |
condition => { |
| 789 |
let attr_inner_tokens = quote! { |
| 790 |
#serde_with_crate_path::Schema::<#type_original, #replacement_type> |
| 791 |
}; |
| 792 |
let attr_inner_tokens = attr_inner_tokens.to_string(); |
| 793 |
let attr = match condition { |
| 794 |
SchemaFieldConfig::False => unreachable!(), |
| 795 |
SchemaFieldConfig::True => { |
| 796 |
parse_quote! { #[schemars(with = #attr_inner_tokens)] } |
| 797 |
} |
| 798 |
SchemaFieldConfig::Lazy(SchemaFieldCondition(condition)) => { |
| 799 |
parse_quote! { |
| 800 |
#[cfg_attr( |
| 801 |
#condition, |
| 802 |
schemars(with = #attr_inner_tokens)) |
| 803 |
] |
| 804 |
} |
| 805 |
} |
| 806 |
}; |
| 807 |
|
| 808 |
field.attrs.push(attr); |
| 809 |
} |
| 810 |
} |
| 811 |
} |
| 812 |
} |
| 813 |
} |
| 814 |
if let Some(type_) = &serde_as_options.deserialize_as { |
| 815 |
emit_borrow_annotation(&serde_options, type_, field); |
| 816 |
emit_default_annotation(&serde_as_options, &serde_options, type_, field); |
| 817 |
|
| 818 |
let replacement_type = replace_infer_type_with_type(type_.clone(), type_same); |
| 819 |
let attr_inner_tokens = |
| 820 |
quote!(#serde_with_crate_path::As::<#replacement_type>::deserialize).to_string(); |
| 821 |
let attr = parse_quote!(#[serde(deserialize_with = #attr_inner_tokens)]); |
| 822 |
field.attrs.push(attr); |
| 823 |
} |
| 824 |
if let Some(type_) = serde_as_options.serialize_as { |
| 825 |
let replacement_type = replace_infer_type_with_type(type_.clone(), type_same); |
| 826 |
let attr_inner_tokens = |
| 827 |
quote!(#serde_with_crate_path::As::<#replacement_type>::serialize).to_string(); |
| 828 |
let attr = parse_quote!(#[serde(serialize_with = #attr_inner_tokens)]); |
| 829 |
field.attrs.push(attr); |
| 830 |
} |
| 831 |
|
| 832 |
Ok(()) |
| 833 |
} |
| 834 |
|
| 835 |
/// Recursively replace all occurrences of `_` with `replacement` in a [Type][] |
| 836 |
/// |
| 837 |
/// The [`serde_as`][macro@serde_as] macro allows to use the infer type, i.e., `_`, as shortcut for |
| 838 |
/// `serde_with::As`. This function replaces all occurrences of the infer type with another type. |
| 839 |
fn replace_infer_type_with_type(to_replace: Type, replacement: &Type) -> Type { |
| 840 |
match to_replace { |
| 841 |
// Base case |
| 842 |
// Replace the infer type with the actual replacement type |
| 843 |
Type::Infer(_) => replacement.clone(), |
| 844 |
|
| 845 |
// Recursive cases |
| 846 |
// Iterate through all positions where a type could occur and recursively call this function |
| 847 |
Type::Array(mut inner) => { |
| 848 |
*inner.elem = replace_infer_type_with_type(*inner.elem, replacement); |
| 849 |
Type::Array(inner) |
| 850 |
} |
| 851 |
Type::Group(mut inner) => { |
| 852 |
*inner.elem = replace_infer_type_with_type(*inner.elem, replacement); |
| 853 |
Type::Group(inner) |
| 854 |
} |
| 855 |
Type::Never(inner) => Type::Never(inner), |
| 856 |
Type::Paren(mut inner) => { |
| 857 |
*inner.elem = replace_infer_type_with_type(*inner.elem, replacement); |
| 858 |
Type::Paren(inner) |
| 859 |
} |
| 860 |
Type::Path(mut inner) => { |
| 861 |
if let Some(Pair::End(mut t)) | Some(Pair::Punctuated(mut t, _)) = |
| 862 |
inner.path.segments.pop() |
| 863 |
{ |
| 864 |
t.arguments = match t.arguments { |
| 865 |
PathArguments::None => PathArguments::None, |
| 866 |
PathArguments::AngleBracketed(mut inner) => { |
| 867 |
// Iterate over the args between the angle brackets |
| 868 |
inner.args = inner |
| 869 |
.args |
| 870 |
.into_iter() |
| 871 |
.map(|generic_argument| match generic_argument { |
| 872 |
// replace types within the generics list, but leave other stuff |
| 873 |
// like lifetimes untouched |
| 874 |
GenericArgument::Type(type_) => GenericArgument::Type( |
| 875 |
replace_infer_type_with_type(type_, replacement), |
| 876 |
), |
| 877 |
ga => ga, |
| 878 |
}) |
| 879 |
.collect(); |
| 880 |
PathArguments::AngleBracketed(inner) |
| 881 |
} |
| 882 |
PathArguments::Parenthesized(mut inner) => { |
| 883 |
inner.inputs = inner |
| 884 |
.inputs |
| 885 |
.into_iter() |
| 886 |
.map(|type_| replace_infer_type_with_type(type_, replacement)) |
| 887 |
.collect(); |
| 888 |
inner.output = match inner.output { |
| 889 |
ReturnType::Type(arrow, mut type_) => { |
| 890 |
*type_ = replace_infer_type_with_type(*type_, replacement); |
| 891 |
ReturnType::Type(arrow, type_) |
| 892 |
} |
| 893 |
default => default, |
| 894 |
}; |
| 895 |
PathArguments::Parenthesized(inner) |
| 896 |
} |
| 897 |
}; |
| 898 |
inner.path.segments.push(t); |
| 899 |
} |
| 900 |
Type::Path(inner) |
| 901 |
} |
| 902 |
Type::Ptr(mut inner) => { |
| 903 |
*inner.elem = replace_infer_type_with_type(*inner.elem, replacement); |
| 904 |
Type::Ptr(inner) |
| 905 |
} |
| 906 |
Type::Reference(mut inner) => { |
| 907 |
*inner.elem = replace_infer_type_with_type(*inner.elem, replacement); |
| 908 |
Type::Reference(inner) |
| 909 |
} |
| 910 |
Type::Slice(mut inner) => { |
| 911 |
*inner.elem = replace_infer_type_with_type(*inner.elem, replacement); |
| 912 |
Type::Slice(inner) |
| 913 |
} |
| 914 |
Type::Tuple(mut inner) => { |
| 915 |
inner.elems = inner |
| 916 |
.elems |
| 917 |
.into_pairs() |
| 918 |
.map(|pair| match pair { |
| 919 |
Pair::Punctuated(type_, p) => { |
| 920 |
Pair::Punctuated(replace_infer_type_with_type(type_, replacement), p) |
| 921 |
} |
| 922 |
Pair::End(type_) => Pair::End(replace_infer_type_with_type(type_, replacement)), |
| 923 |
}) |
| 924 |
.collect(); |
| 925 |
Type::Tuple(inner) |
| 926 |
} |
| 927 |
|
| 928 |
// Pass unknown types or non-handleable types (e.g., bare Fn) without performing any |
| 929 |
// replacements |
| 930 |
type_ => type_, |
| 931 |
} |
| 932 |
} |
| 933 |
|
| 934 |
/// Check if a type ending in the `syn::Ident` `embedded_type` is contained in `type_`. |
| 935 |
fn has_type_embedded(type_: &Type, embedded_type: &syn::Ident) -> bool { |
| 936 |
match type_ { |
| 937 |
// Base cases |
| 938 |
Type::Infer(_) => false, |
| 939 |
Type::Never(_inner) => false, |
| 940 |
|
| 941 |
// Recursive cases |
| 942 |
// Iterate through all positions where a type could occur and recursively call this function |
| 943 |
Type::Array(inner) => has_type_embedded(&inner.elem, embedded_type), |
| 944 |
Type::Group(inner) => has_type_embedded(&inner.elem, embedded_type), |
| 945 |
Type::Paren(inner) => has_type_embedded(&inner.elem, embedded_type), |
| 946 |
Type::Path(inner) => { |
| 947 |
match inner.path.segments.last() { |
| 948 |
Some(t) => { |
| 949 |
if t.ident == *embedded_type { |
| 950 |
return true; |
| 951 |
} |
| 952 |
|
| 953 |
match &t.arguments { |
| 954 |
PathArguments::None => false, |
| 955 |
PathArguments::AngleBracketed(inner) => { |
| 956 |
// Iterate over the args between the angle brackets |
| 957 |
inner |
| 958 |
.args |
| 959 |
.iter() |
| 960 |
.any(|generic_argument| match generic_argument { |
| 961 |
// replace types within the generics list, but leave other stuff |
| 962 |
// like lifetimes untouched |
| 963 |
GenericArgument::Type(type_) => { |
| 964 |
has_type_embedded(type_, embedded_type) |
| 965 |
} |
| 966 |
_ga => false, |
| 967 |
}) |
| 968 |
} |
| 969 |
PathArguments::Parenthesized(inner) => { |
| 970 |
inner |
| 971 |
.inputs |
| 972 |
.iter() |
| 973 |
.any(|type_| has_type_embedded(type_, embedded_type)) |
| 974 |
|| match &inner.output { |
| 975 |
ReturnType::Type(_arrow, type_) => { |
| 976 |
has_type_embedded(type_, embedded_type) |
| 977 |
} |
| 978 |
_default => false, |
| 979 |
} |
| 980 |
} |
| 981 |
} |
| 982 |
} |
| 983 |
None => false, |
| 984 |
} |
| 985 |
} |
| 986 |
Type::Ptr(inner) => has_type_embedded(&inner.elem, embedded_type), |
| 987 |
Type::Reference(inner) => has_type_embedded(&inner.elem, embedded_type), |
| 988 |
Type::Slice(inner) => has_type_embedded(&inner.elem, embedded_type), |
| 989 |
Type::Tuple(inner) => inner.elems.pairs().any(|pair| match pair { |
| 990 |
Pair::Punctuated(type_, _) | Pair::End(type_) => { |
| 991 |
has_type_embedded(type_, embedded_type) |
| 992 |
} |
| 993 |
}), |
| 994 |
|
| 995 |
// Pass unknown types or non-handleable types (e.g., bare Fn) without performing any |
| 996 |
// replacements |
| 997 |
_type_ => false, |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
/// Deserialize value by using its [`FromStr`] implementation |
| 1002 |
/// |
| 1003 |
/// This is an alternative way to implement `Deserialize` for types, which also implement |
| 1004 |
/// [`FromStr`] by deserializing the type from string. Ensure that the struct/enum also implements |
| 1005 |
/// [`FromStr`]. If the implementation is missing, you will get an error message like |
| 1006 |
/// ```text |
| 1007 |
/// error[E0277]: the trait bound `Struct: std::str::FromStr` is not satisfied |
| 1008 |
/// ``` |
| 1009 |
/// Additionally, `FromStr::Err` **must** implement [`Display`] as otherwise you will see a rather |
| 1010 |
/// unhelpful error message |
| 1011 |
/// |
| 1012 |
/// Serialization with [`Display`] is available with the matching [`SerializeDisplay`] derive. |
| 1013 |
/// |
| 1014 |
/// # Attributes |
| 1015 |
/// |
| 1016 |
/// Attributes for the derive can be specified via the `#[serde_with(...)]` attribute on the struct |
| 1017 |
/// or enum. Currently, these arguments to the attribute are possible: |
| 1018 |
/// |
| 1019 |
/// * **`#[serde_with(crate = "...")]`**: This allows using `DeserializeFromStr` when `serde_with` |
| 1020 |
/// is not available from the crate root. This happens while [renaming dependencies in |
| 1021 |
/// Cargo.toml][cargo-toml-rename] or when re-exporting the macro from a different crate. |
| 1022 |
/// |
| 1023 |
/// This argument is analogue to [serde's crate argument][serde-crate] and the [crate argument |
| 1024 |
/// to `serde_as`][serde-as-crate]. |
| 1025 |
/// |
| 1026 |
/// # Example |
| 1027 |
/// |
| 1028 |
/// ```rust,ignore |
| 1029 |
/// use std::str::FromStr; |
| 1030 |
/// |
| 1031 |
/// #[derive(DeserializeFromStr)] |
| 1032 |
/// struct A { |
| 1033 |
/// a: u32, |
| 1034 |
/// b: bool, |
| 1035 |
/// } |
| 1036 |
/// |
| 1037 |
/// impl FromStr for A { |
| 1038 |
/// type Err = String; |
| 1039 |
/// |
| 1040 |
/// /// Parse a value like `123<>true` |
| 1041 |
/// fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 1042 |
/// let mut parts = s.split("<>"); |
| 1043 |
/// let number = parts |
| 1044 |
/// .next() |
| 1045 |
/// .ok_or_else(|| "Missing first value".to_string())? |
| 1046 |
/// .parse() |
| 1047 |
/// .map_err(|err: ParseIntError| err.to_string())?; |
| 1048 |
/// let bool = parts |
| 1049 |
/// .next() |
| 1050 |
/// .ok_or_else(|| "Missing second value".to_string())? |
| 1051 |
/// .parse() |
| 1052 |
/// .map_err(|err: ParseBoolError| err.to_string())?; |
| 1053 |
/// Ok(Self { a: number, b: bool }) |
| 1054 |
/// } |
| 1055 |
/// } |
| 1056 |
/// |
| 1057 |
/// let a: A = serde_json::from_str("\"159<>true\"").unwrap(); |
| 1058 |
/// assert_eq!(A { a: 159, b: true }, a); |
| 1059 |
/// ``` |
| 1060 |
/// |
| 1061 |
/// [`Display`]: std::fmt::Display |
| 1062 |
/// [`FromStr`]: std::str::FromStr |
| 1063 |
/// [cargo-toml-rename]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml |
| 1064 |
/// [serde-as-crate]: https://docs.rs/serde_with/3.12.0/serde_with/guide/serde_as/index.html#re-exporting-serde_as |
| 1065 |
/// [serde-crate]: https://serde.rs/container-attrs.html#crate |
| 1066 |
#[proc_macro_derive(DeserializeFromStr, attributes(serde_with))] |
| 1067 |
pub fn derive_deserialize_fromstr(item: TokenStream) -> TokenStream { |
| 1068 |
let input: DeriveInput = parse_macro_input!(item); |
| 1069 |
let derive_options = match DeriveOptions::from_derive_input(&input) { |
| 1070 |
Ok(opt) => opt, |
| 1071 |
Err(err) => { |
| 1072 |
return err; |
| 1073 |
} |
| 1074 |
}; |
| 1075 |
TokenStream::from(deserialize_fromstr( |
| 1076 |
input, |
| 1077 |
derive_options.get_serde_with_path(), |
| 1078 |
)) |
| 1079 |
} |
| 1080 |
|
| 1081 |
fn deserialize_fromstr(mut input: DeriveInput, serde_with_crate_path: Path) -> TokenStream2 { |
| 1082 |
let ident = input.ident; |
| 1083 |
let where_clause = &mut input.generics.make_where_clause().predicates; |
| 1084 |
where_clause.push(parse_quote!(Self: #serde_with_crate_path::__private__::FromStr)); |
| 1085 |
where_clause.push(parse_quote!( |
| 1086 |
<Self as #serde_with_crate_path::__private__::FromStr>::Err: #serde_with_crate_path::__private__::Display |
| 1087 |
)); |
| 1088 |
let (de_impl_generics, ty_generics, where_clause) = split_with_de_lifetime(&input.generics); |
| 1089 |
quote! { |
| 1090 |
#[automatically_derived] |
| 1091 |
impl #de_impl_generics #serde_with_crate_path::serde::Deserialize<'de> for #ident #ty_generics #where_clause { |
| 1092 |
fn deserialize<__D>(deserializer: __D) -> #serde_with_crate_path::__private__::Result<Self, __D::Error> |
| 1093 |
where |
| 1094 |
__D: #serde_with_crate_path::serde::Deserializer<'de>, |
| 1095 |
{ |
| 1096 |
struct Helper<__S>(#serde_with_crate_path::__private__::PhantomData<__S>); |
| 1097 |
|
| 1098 |
impl<'de, __S> #serde_with_crate_path::serde::de::Visitor<'de> for Helper<__S> |
| 1099 |
where |
| 1100 |
__S: #serde_with_crate_path::__private__::FromStr, |
| 1101 |
<__S as #serde_with_crate_path::__private__::FromStr>::Err: #serde_with_crate_path::__private__::Display, |
| 1102 |
{ |
| 1103 |
type Value = __S; |
| 1104 |
|
| 1105 |
fn expecting(&self, formatter: &mut #serde_with_crate_path::core::fmt::Formatter<'_>) -> #serde_with_crate_path::core::fmt::Result { |
| 1106 |
#serde_with_crate_path::__private__::Display::fmt("a string", formatter) |
| 1107 |
} |
| 1108 |
|
| 1109 |
fn visit_str<__E>( |
| 1110 |
self, |
| 1111 |
value: &str |
| 1112 |
) -> #serde_with_crate_path::__private__::Result<Self::Value, __E> |
| 1113 |
where |
| 1114 |
__E: #serde_with_crate_path::serde::de::Error, |
| 1115 |
{ |
| 1116 |
value.parse::<Self::Value>().map_err(#serde_with_crate_path::serde::de::Error::custom) |
| 1117 |
} |
| 1118 |
|
| 1119 |
fn visit_bytes<__E>( |
| 1120 |
self, |
| 1121 |
value: &[u8] |
| 1122 |
) -> #serde_with_crate_path::__private__::Result<Self::Value, __E> |
| 1123 |
where |
| 1124 |
__E: #serde_with_crate_path::serde::de::Error, |
| 1125 |
{ |
| 1126 |
let utf8 = #serde_with_crate_path::core::str::from_utf8(value).map_err(#serde_with_crate_path::serde::de::Error::custom)?; |
| 1127 |
self.visit_str(utf8) |
| 1128 |
} |
| 1129 |
} |
| 1130 |
|
| 1131 |
deserializer.deserialize_str(Helper(#serde_with_crate_path::__private__::PhantomData)) |
| 1132 |
} |
| 1133 |
} |
| 1134 |
} |
| 1135 |
} |
| 1136 |
|
| 1137 |
/// Serialize value by using it's [`Display`] implementation |
| 1138 |
/// |
| 1139 |
/// This is an alternative way to implement `Serialize` for types, which also implement [`Display`] |
| 1140 |
/// by serializing the type as string. Ensure that the struct/enum also implements [`Display`]. |
| 1141 |
/// If the implementation is missing, you will get an error message like |
| 1142 |
/// ```text |
| 1143 |
/// error[E0277]: `Struct` doesn't implement `std::fmt::Display` |
| 1144 |
/// ``` |
| 1145 |
/// |
| 1146 |
/// Deserialization with [`FromStr`] is available with the matching [`DeserializeFromStr`] derive. |
| 1147 |
/// |
| 1148 |
/// # Attributes |
| 1149 |
/// |
| 1150 |
/// Attributes for the derive can be specified via the `#[serde_with(...)]` attribute on the struct |
| 1151 |
/// or enum. Currently, these arguments to the attribute are possible: |
| 1152 |
/// |
| 1153 |
/// * **`#[serde_with(crate = "...")]`**: This allows using `SerializeDisplay` when `serde_with` is |
| 1154 |
/// not available from the crate root. This happens while [renaming dependencies in |
| 1155 |
/// Cargo.toml][cargo-toml-rename] or when re-exporting the macro from a different crate. |
| 1156 |
/// |
| 1157 |
/// This argument is analogue to [serde's crate argument][serde-crate] and the [crate argument |
| 1158 |
/// to `serde_as`][serde-as-crate]. |
| 1159 |
/// |
| 1160 |
/// # Example |
| 1161 |
/// |
| 1162 |
/// ```rust,ignore |
| 1163 |
/// use std::fmt; |
| 1164 |
/// |
| 1165 |
/// #[derive(SerializeDisplay)] |
| 1166 |
/// struct A { |
| 1167 |
/// a: u32, |
| 1168 |
/// b: bool, |
| 1169 |
/// } |
| 1170 |
/// |
| 1171 |
/// impl fmt::Display for A { |
| 1172 |
/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1173 |
/// write!(f, "{}<>{}", self.a, self.b) |
| 1174 |
/// } |
| 1175 |
/// } |
| 1176 |
/// |
| 1177 |
/// let a = A { a: 123, b: false }; |
| 1178 |
/// assert_eq!(r#""123<>false""#, serde_json::to_string(&a).unwrap()); |
| 1179 |
/// ``` |
| 1180 |
/// |
| 1181 |
/// [`Display`]: std::fmt::Display |
| 1182 |
/// [`FromStr`]: std::str::FromStr |
| 1183 |
/// [cargo-toml-rename]: https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#renaming-dependencies-in-cargotoml |
| 1184 |
/// [serde-as-crate]: https://docs.rs/serde_with/3.12.0/serde_with/guide/serde_as/index.html#re-exporting-serde_as |
| 1185 |
/// [serde-crate]: https://serde.rs/container-attrs.html#crate |
| 1186 |
#[proc_macro_derive(SerializeDisplay, attributes(serde_with))] |
| 1187 |
pub fn derive_serialize_display(item: TokenStream) -> TokenStream { |
| 1188 |
let input: DeriveInput = parse_macro_input!(item); |
| 1189 |
let derive_options = match DeriveOptions::from_derive_input(&input) { |
| 1190 |
Ok(opt) => opt, |
| 1191 |
Err(err) => { |
| 1192 |
return err; |
| 1193 |
} |
| 1194 |
}; |
| 1195 |
TokenStream::from(serialize_display( |
| 1196 |
input, |
| 1197 |
derive_options.get_serde_with_path(), |
| 1198 |
)) |
| 1199 |
} |
| 1200 |
|
| 1201 |
fn serialize_display(mut input: DeriveInput, serde_with_crate_path: Path) -> TokenStream2 { |
| 1202 |
let ident = input.ident; |
| 1203 |
input |
| 1204 |
.generics |
| 1205 |
.make_where_clause() |
| 1206 |
.predicates |
| 1207 |
.push(parse_quote!(Self: #serde_with_crate_path::__private__::Display)); |
| 1208 |
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); |
| 1209 |
quote! { |
| 1210 |
#[automatically_derived] |
| 1211 |
impl #impl_generics #serde_with_crate_path::serde::Serialize for #ident #ty_generics #where_clause { |
| 1212 |
fn serialize<__S>( |
| 1213 |
&self, |
| 1214 |
serializer: __S |
| 1215 |
) -> #serde_with_crate_path::__private__::Result<__S::Ok, __S::Error> |
| 1216 |
where |
| 1217 |
__S: #serde_with_crate_path::serde::Serializer, |
| 1218 |
{ |
| 1219 |
serializer.collect_str(&self) |
| 1220 |
} |
| 1221 |
} |
| 1222 |
} |
| 1223 |
} |
| 1224 |
|
| 1225 |
#[doc(hidden)] |
| 1226 |
/// Private function. Not part of the public API |
| 1227 |
/// |
| 1228 |
/// The only task of this derive macro is to consume any `serde_as` attributes and turn them into |
| 1229 |
/// inert attributes. This allows the serde_as macro to keep the field attributes without causing |
| 1230 |
/// compiler errors. The intend is that keeping the field attributes allows downstream crates to |
| 1231 |
/// consume and act on them without causing an ordering dependency to the serde_as macro. |
| 1232 |
/// |
| 1233 |
/// Otherwise, downstream proc-macros would need to be placed *in front of* the main `#[serde_as]` |
| 1234 |
/// attribute, since otherwise the field attributes would already be stripped off. |
| 1235 |
/// |
| 1236 |
/// More details about the use-cases in the GitHub discussion: <https://github.com/jonasbb/serde_with/discussions/260>. |
| 1237 |
#[proc_macro_derive( |
| 1238 |
__private_consume_serde_as_attributes, |
| 1239 |
attributes(serde_as, serde_with) |
| 1240 |
)] |
| 1241 |
pub fn __private_consume_serde_as_attributes(_: TokenStream) -> TokenStream { |
| 1242 |
TokenStream::new() |
| 1243 |
} |
| 1244 |
|
| 1245 |
/// Apply attributes to all fields with matching types |
| 1246 |
/// |
| 1247 |
/// Whenever you experience the need to apply the same attributes to multiple fields, you can use |
| 1248 |
/// this macro. It allows you to specify a list of types and a list of attributes. |
| 1249 |
/// Each field with a "matching" type will then get the attributes applied. |
| 1250 |
/// The `apply` attribute must be placed *before* any consuming attributes, such as `derive` or |
| 1251 |
/// `serde_as`, because Rust expands all attributes in order. |
| 1252 |
/// |
| 1253 |
/// For example, if your struct or enum contains many `Option<T>` fields, but you do not want to |
| 1254 |
/// serialize `None` values, you can use this macro to apply the `#[serde(skip_serializing_if = |
| 1255 |
/// "Option::is_none")]` attribute to all fields of type `Option<T>`. |
| 1256 |
/// |
| 1257 |
/// ```rust |
| 1258 |
/// # use serde_with_macros as serde_with; |
| 1259 |
/// #[serde_with::apply( |
| 1260 |
/// # crate="serde_with", |
| 1261 |
/// Option => #[serde(skip_serializing_if = "Option::is_none")], |
| 1262 |
/// )] |
| 1263 |
/// #[derive(serde::Serialize)] |
| 1264 |
/// # #[derive(Default)] |
| 1265 |
/// struct Data { |
| 1266 |
/// a: Option<String>, |
| 1267 |
/// b: Option<u64>, |
| 1268 |
/// c: Option<String>, |
| 1269 |
/// d: Option<bool>, |
| 1270 |
/// } |
| 1271 |
/// # |
| 1272 |
/// # assert_eq!("{}", serde_json::to_string(&Data::default()).unwrap()); |
| 1273 |
/// ``` |
| 1274 |
/// |
| 1275 |
/// Each rule starts with a type pattern, specifying which fields to match and a list of attributes |
| 1276 |
/// to apply. Multiple rules can be provided in a single `apply` attribute. |
| 1277 |
/// |
| 1278 |
/// ```rust |
| 1279 |
/// # use serde_with_macros as serde_with; |
| 1280 |
/// #[serde_with::apply( |
| 1281 |
/// # crate="serde_with", |
| 1282 |
/// Option => #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")], |
| 1283 |
/// Option<bool> => #[serde(rename = "bool")], |
| 1284 |
/// )] |
| 1285 |
/// # #[derive(serde::Serialize)] |
| 1286 |
/// # #[derive(Default)] |
| 1287 |
/// # struct Data { |
| 1288 |
/// # a: Option<String>, |
| 1289 |
/// # b: Option<u64>, |
| 1290 |
/// # c: Option<String>, |
| 1291 |
/// # d: Option<bool>, |
| 1292 |
/// # } |
| 1293 |
/// # |
| 1294 |
/// # assert_eq!("{}", serde_json::to_string(&Data::default()).unwrap()); |
| 1295 |
/// ``` |
| 1296 |
/// |
| 1297 |
/// ## Type Patterns |
| 1298 |
/// |
| 1299 |
/// The type pattern left of the `=>` specifies which fields to match. |
| 1300 |
/// |
| 1301 |
/// | Type Pattern | Matching Types | Notes | |
| 1302 |
/// | :---------------------- | ---------------------------------------------------: | :------------------------------------------------------------------------------ | |
| 1303 |
/// | `_` | `Option<bool>`<br>`BTreeMap<&'static str, Vec<u32>>` | `_` matches all fields. | |
| 1304 |
/// | `Option` | `Option<bool>`<br>`Option<String>` | A missing generic is compatible with any generic arguments. | |
| 1305 |
/// | `Option<bool>` | `Option<bool>` | A fully specified type only matches exactly. | |
| 1306 |
/// | `BTreeMap<String, u32>` | `BTreeMap<String, u32>` | A fully specified type only matches exactly. | |
| 1307 |
/// | `BTreeMap<String, _>` | `BTreeMap<String, u32>`<br>`BTreeMap<String, bool>` | Any `String` key `BTreeMap` matches, as the value is using the `_` placeholder. | |
| 1308 |
/// | `[u8; _]` | `[u8; 1]`<br>`[u8; N]` | `_` also works as a placeholder for any array length. | |
| 1309 |
/// |
| 1310 |
/// ## Opt-out for Individual Fields |
| 1311 |
/// |
| 1312 |
/// The `apply` attribute will find all fields with a compatible type. |
| 1313 |
/// This can be overly eager and a different set of attributes might be required for a specific |
| 1314 |
/// field. You can opt-out of the `apply` attribute by adding the `#[serde_with(skip_apply)]` |
| 1315 |
/// attribute to the field. This will prevent any `apply` to apply to this field. |
| 1316 |
/// If two rules apply to the same field, it is impossible to opt-out of only a single one. |
| 1317 |
/// In this case the attributes must be applied to the field manually. |
| 1318 |
/// |
| 1319 |
/// ```rust |
| 1320 |
/// # use serde_json::json; |
| 1321 |
/// # use serde_with_macros as serde_with; |
| 1322 |
/// #[serde_with::apply( |
| 1323 |
/// # crate="serde_with", |
| 1324 |
/// Option => #[serde(skip_serializing_if = "Option::is_none")], |
| 1325 |
/// )] |
| 1326 |
/// #[derive(serde::Serialize)] |
| 1327 |
/// struct Data { |
| 1328 |
/// a: Option<String>, |
| 1329 |
/// #[serde_with(skip_apply)] |
| 1330 |
/// always_serialize_this_field: Option<u64>, |
| 1331 |
/// c: Option<String>, |
| 1332 |
/// d: Option<bool>, |
| 1333 |
/// } |
| 1334 |
/// |
| 1335 |
/// let data = Data { |
| 1336 |
/// a: None, |
| 1337 |
/// always_serialize_this_field: None, |
| 1338 |
/// c: None, |
| 1339 |
/// d: None, |
| 1340 |
/// }; |
| 1341 |
/// |
| 1342 |
/// // serializes into this JSON: |
| 1343 |
/// # assert_eq!(json!( |
| 1344 |
/// { |
| 1345 |
/// "always_serialize_this_field": null |
| 1346 |
/// } |
| 1347 |
/// # ), serde_json::to_value(data).unwrap()); |
| 1348 |
/// ``` |
| 1349 |
/// |
| 1350 |
/// # Alternative path to `serde_with` crate |
| 1351 |
/// |
| 1352 |
/// If `serde_with` is not available at the default path, its path should be specified with the |
| 1353 |
/// `crate` argument. See [re-exporting `serde_as`] for more use case information. |
| 1354 |
/// |
| 1355 |
/// ```rust,ignore |
| 1356 |
/// #[serde_with::apply( |
| 1357 |
/// crate = "::some_other_lib::serde_with" |
| 1358 |
/// Option => #[serde(skip_serializing_if = "Option::is_none")], |
| 1359 |
/// )] |
| 1360 |
/// #[derive(serde::Serialize)] |
| 1361 |
/// struct Data { |
| 1362 |
/// a: Option<String>, |
| 1363 |
/// b: Option<u64>, |
| 1364 |
/// c: Option<String>, |
| 1365 |
/// d: Option<bool>, |
| 1366 |
/// } |
| 1367 |
/// ``` |
| 1368 |
#[proc_macro_attribute] |
| 1369 |
pub fn apply(args: TokenStream, input: TokenStream) -> TokenStream { |
| 1370 |
apply::apply(args, input) |
| 1371 |
} |