1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
/*!
# Processing of enum declarations
This module contains the main code for implementing the derive macros from
this crate on `enum` items.
It is thus the counterpart to [`crate::structs`].
*/
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::*;
use crate::common::{build_prepare, build_validate, ItemDef};
use crate::compound::Compound;
use crate::error_message::ParentRef;
use crate::meta::{Flag, Name, NamespaceRef, StaticNamespace, XmlCompoundMeta};
use crate::structs::StructInner;
/// Build the necessary objects to rebind all enum fields to collision-free
/// identifiers.
///
/// Takes an iterator over members of the enum's compound and returns, in
/// order:
///
/// - A vector of these identifiers.
/// - A vector with expressions containing the rebound idenifiers.
/// - A function which maps the original identifiers to their rebound
/// versions.
fn build_ident_mapping<I: Iterator<Item = Member>>(
refs: I,
) -> (Vec<Member>, Vec<Expr>, Box<dyn FnMut(Member) -> Expr>) {
let map_ident = |ident: Member| -> Expr {
Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: Path {
leading_colon: None,
segments: [PathSegment::from(quote::format_ident!("__field_{}", ident))]
.into_iter()
.collect(),
},
})
};
let mut orig_names = Vec::with_capacity(refs.size_hint().1.unwrap_or(0));
let mut mapped_names = Vec::with_capacity(orig_names.capacity());
for field_ref in refs {
orig_names.push(field_ref.clone());
mapped_names.push(map_ident(field_ref));
}
(orig_names, mapped_names, Box::new(map_ident))
}
/// Variant of an enum which switches on a string value extracted from the XML
/// element.
///
/// The caller of the respective methods decides what string the variant
/// matches against and how that match is carried out.
#[derive(Debug)]
struct StrMatchedVariant {
/// The string to match against.
value: LitStr,
/// The identifier of the enum variant.
ident: Ident,
/// The `fallback` flag on the enum variant.
fallback: Flag,
/// The contents of the enum variant.
inner: Compound,
}
impl StrMatchedVariant {
fn prevalidate(meta: &mut XmlCompoundMeta) -> Result<()> {
if let Some(namespace) = meta.namespace.take() {
return Err(Error::new_spanned(
namespace,
"`namespace` not allowed on enum variants.",
));
}
if let Some(attribute) = meta.attribute.take() {
return Err(Error::new_spanned(
attribute,
"`attribute` not allowed on enum variants.",
));
}
if let Flag::Present(transparent) = meta.transparent.take() {
return Err(Error::new(
transparent,
"`transparent` not allowed on enum variants in enums with a fixed namespace.",
));
}
if let Flag::Present(exhaustive) = meta.exhaustive.take() {
return Err(Error::new(
exhaustive,
"`exhaustive` not allowed on enum variants.",
));
}
if let Some(validate) = meta.validate.take() {
return Err(Error::new_spanned(
validate,
"`validate` not allowed on enum variants.",
));
}
if let Some(prepare) = meta.prepare.take() {
return Err(Error::new_spanned(
prepare,
"`validate` not allowed on enum variants.",
));
}
if let Flag::Present(debug) = meta.debug.take() {
return Err(Error::new(debug, "`debug` not allowed on enum variants."));
}
Ok(())
}
/// Parse a [`syn::Variant`] as XML name switched variant.
fn new_xml_name_switched(variant: &Variant) -> Result<Self> {
let mut meta = XmlCompoundMeta::parse_from_attributes(&variant.attrs)?;
Self::prevalidate(&mut meta)?;
if let Some(value) = meta.value {
return Err(Error::new_spanned(
value,
"`value` not allowed on enum variants inside enums matching on XML name.",
));
}
let name = if let Some(name) = meta.name {
name.into()
} else {
return Err(Error::new(
meta.span,
"`name` is required on enum variants in enums with a fixed namespace.",
));
};
let fallback = meta.fallback;
Ok(Self {
value: name,
ident: variant.ident.clone(),
fallback,
inner: Compound::from_fields(
meta.on_unknown_child,
meta.on_unknown_attribute,
&variant.fields,
)?,
})
}
/// Parse a [`syn::Variant`] as XML attribute value switched variant.
fn new_xml_attribute_switched(variant: &Variant) -> Result<Self> {
let mut meta = XmlCompoundMeta::parse_from_attributes(&variant.attrs)?;
Self::prevalidate(&mut meta)?;
if let Some(name) = meta.name {
return Err(Error::new_spanned(
name,
"`name` not allowed on enum variants inside enums matching on attribute values.",
));
}
let Some(value) = meta.value else {
return Err(Error::new(
meta.span,
"`value` is required on enum variants in enums matching on attribute values.",
));
};
let fallback = meta.fallback;
Ok(Self {
value,
ident: variant.ident.clone(),
fallback,
inner: Compound::from_fields(
meta.on_unknown_child,
meta.on_unknown_attribute,
&variant.fields,
)?,
})
}
}
/// Variant of an enum where each variant has completely independent matching.
#[derive(Debug)]
struct DynamicVariant {
/// The identifier of the enum variant.
ident: Ident,
/// The enum variant's definition.
///
/// The implementation of [`StructInner`] can be reused completely, as the
/// variant has to cover all of its matching logic.
inner: StructInner,
}
impl DynamicVariant {
/// Parse a [`syn::Variant`] as dynamic enum variant.
fn new(variant: &Variant) -> Result<Self> {
let ident = variant.ident.clone();
let mut meta = XmlCompoundMeta::parse_from_attributes(&variant.attrs)?;
if let Flag::Present(fallback) = meta.fallback.take() {
return Err(Error::new(
fallback,
"`fallback` cannot be used in dynamic enums.",
));
}
if let Flag::Present(exhaustive) = meta.exhaustive.take() {
return Err(Error::new(
exhaustive,
"`exhaustive` not allowed on enum variants.",
));
}
if let Some(validate) = meta.validate.take() {
return Err(Error::new_spanned(
validate,
"`validate` not allowed on enum variants.",
));
}
if let Some(prepare) = meta.prepare.take() {
return Err(Error::new_spanned(
prepare,
"`validate` not allowed on enum variants.",
));
}
if let Flag::Present(debug) = meta.debug.take() {
return Err(Error::new(debug, "`debug` not allowed on enum variants."));
}
let inner = StructInner::new(meta, &variant.fields)?;
Ok(Self { ident, inner })
}
}
/// An enum which switches on the XML element's name, with a fixed namespace.
#[derive(Debug)]
struct XmlNameSwitched {
/// The exhaustive flag, if set on the enum.
///
/// If this flag is set, the enum considers itself authoritative for its
/// namespace.
///
/// Then, if an XML element matching the namespace but none of the
/// variants is encountered, a hard parse error with an appropriate error
/// message is emitted. That prevents parsing the XML element as other
/// fields of a parent struct (such as #[xml(elements)]`).
///
/// This can be useful in some circumstances.
exhaustive: Flag,
/// The namespace the enum's XML element resides in.
namespace: StaticNamespace,
/// The enum's variants.
variants: Vec<StrMatchedVariant>,
}
impl XmlNameSwitched {
/// Construct a new XML name switched enum from parts.
///
/// - `exhaustive` must be the exhaustive flag (see [`Self::exhaustive`]
/// for details).
///
/// - `namespace` must be the XML namespace of the enum.
///
/// - `input` must be an iterator emitting borrowed [`syn::Variant`]
/// structs to process.
fn new<'x, I: Iterator<Item = &'x Variant>>(
exhaustive: Flag,
namespace: StaticNamespace,
input: I,
) -> Result<Self> {
let mut variants = Vec::with_capacity(input.size_hint().1.unwrap_or(0));
let mut had_fallback = false;
for variant in input {
let variant = StrMatchedVariant::new_xml_name_switched(variant)?;
if let Flag::Present(fallback) = variant.fallback {
if had_fallback {
return Err(syn::Error::new(
fallback,
"only one variant may be a fallback variant",
));
}
had_fallback = true;
}
variants.push(variant);
}
if let Flag::Present(exhaustive) = exhaustive {
if had_fallback {
return Err(syn::Error::new(exhaustive, "exhaustive cannot be sensibly combined with a fallback variant. choose one or the other."));
}
}
Ok(Self {
exhaustive,
namespace,
variants,
})
}
/// Construct an expression which consumes the `minidom::Element` at
/// `residual` and returns a `Result<T, Error>`.
///
/// - `enum_ident` must be the identifier of the enum's type.
/// - `validate` must be a statement which takes a mutable reference to
/// the identifier `result` and `return`'s with an error if it is not
/// acceptable.
/// - `residual` must be the identifier at which the element is found.
fn build_try_from_element(
&self,
enum_ident: &Ident,
validate: Stmt,
residual: &Ident,
) -> Result<TokenStream> {
let xml_namespace = &self.namespace;
let namespace_expr = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: xml_namespace.clone(),
});
let mut fallback = quote! {
_ => Err(::xso::error::Error::TypeMismatch("", "", #residual)),
};
let mut iter = quote! {};
for variant in self.variants.iter() {
let ident = &variant.ident;
let xml_name = &variant.value;
let variant_impl = variant.inner.build_try_from_element(
&(Path {
leading_colon: None,
segments: [
PathSegment::from(enum_ident.clone()),
PathSegment::from(ident.clone()),
]
.into_iter()
.collect(),
}
.into()),
&namespace_expr,
residual,
&[],
)?;
let variant_impl = quote! {
let mut result = #variant_impl;
#validate
Ok(result)
};
if variant.fallback.is_set() {
fallback = quote! {
_ => { #variant_impl },
}
}
iter = quote! {
#iter
#xml_name => { #variant_impl },
};
}
if self.exhaustive.is_set() {
// deliberately overriding fallback fields here --- the constructor
// already rejects this combination
fallback = quote! {
_ => Err(::xso::error::Error::ParseError(concat!("This is not a ", stringify!(#enum_ident), " element."))),
};
}
Ok(quote! {
if #residual.ns() == #xml_namespace {
match #residual.name() {
#iter
#fallback
}
} else {
Err(::xso::error::Error::TypeMismatch("", "", #residual))
}
})
}
/// Construct a token stream which contains the arms of a `match`
/// expression dissecting the enum and building `minidom::Element` objects
/// for each variant.
///
/// `ty_ident` must be the identifier of the enum's type.
fn build_into_element(&self, ty_ident: &Ident) -> Result<TokenStream> {
let namespace_expr = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: self.namespace.clone(),
});
let builder = Ident::new("builder", Span::call_site());
let mut matchers = quote! {};
for variant in self.variants.iter() {
let xml_name = &variant.value;
let path = Path {
leading_colon: None,
segments: [
PathSegment::from(ty_ident.clone()),
PathSegment::from(variant.ident.clone()),
]
.into_iter()
.collect(),
};
let (orig_names, mapped_names, map_ident) =
build_ident_mapping(variant.inner.iter_members());
let into_element = variant.inner.build_into_element(
&(Path::from(ty_ident.clone()).into()),
&namespace_expr,
&builder,
map_ident,
)?;
matchers = quote! {
#matchers
#path { #( #orig_names: #mapped_names ),* } => {
let #builder = ::xso::exports::minidom::Element::builder(
#xml_name,
#namespace_expr,
);
let #builder = #into_element;
#builder.build()
},
};
}
Ok(matchers)
}
}
/// An enum which switches on the value of an attribute of the XML element.
#[derive(Debug)]
struct XmlAttributeSwitched {
/// The namespace the enum's XML element resides in.
namespace: StaticNamespace,
/// The XML name of the element.
name: Name,
/// The name of the XML attribute to read.
attribute_name: LitStr,
/// Function, if any, to normalize the attribute value with, before
/// matching.
normalize_with: Option<Path>,
/// The enum's variants.
variants: Vec<StrMatchedVariant>,
}
impl XmlAttributeSwitched {
/// Construct a new XML name switched enum from parts.
///
/// - `exhaustive` must be the exhaustive flag. Currently, this must be
/// set on [`XmlAttributeSwitched`] enums.
///
/// - `namespace` must be the XML namespace of the enum.
///
/// - `input` must be an iterator emitting borrowed [`syn::Variant`]
/// structs to process.
fn new<'x, I: Iterator<Item = &'x Variant>>(
exhaustive: Flag,
namespace: StaticNamespace,
name: Name,
attribute_name: LitStr,
normalize_with: Option<Path>,
input: I,
) -> Result<Self> {
let mut variants = Vec::with_capacity(input.size_hint().1.unwrap_or(0));
let mut had_fallback = false;
for variant in input {
let variant = StrMatchedVariant::new_xml_attribute_switched(variant)?;
if let Flag::Present(fallback) = variant.fallback {
if had_fallback {
return Err(syn::Error::new(
fallback,
"only one variant may be a fallback variant",
));
}
had_fallback = true;
}
variants.push(variant);
}
if let Flag::Present(exhaustive) = exhaustive {
if had_fallback {
return Err(syn::Error::new(exhaustive, "exhaustive cannot be sensibly combined with a fallback variant. choose one or the other."));
}
} else {
if !had_fallback {
return Err(syn::Error::new_spanned(
attribute_name,
"enums switching on an attribute must be marked exhaustive or have a fallback variant."
));
}
}
Ok(Self {
namespace,
name,
attribute_name,
normalize_with,
variants,
})
}
/// Construct an expression which consumes the `minidom::Element` at
/// `residual` and returns a `Result<T, Error>`.
///
/// - `enum_ident` must be the identifier of the enum's type.
/// - `validate` must be a statement which takes a mutable reference to
/// the identifier `result` and `return`'s with an error if it is not
/// acceptable.
/// - `residual` must be the identifier at which the element is found.
fn build_try_from_element(
&self,
enum_ident: &Ident,
validate: Stmt,
residual: &Ident,
) -> Result<TokenStream> {
let xml_namespace = &self.namespace;
let xml_name = &self.name;
let attribute_name = self.attribute_name.value();
let namespace_expr = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: xml_namespace.clone(),
});
let mut fallback: Option<TokenStream> = None;
let mut iter = quote! {};
for variant in self.variants.iter() {
let ident = &variant.ident;
let xml_name = &variant.value;
let variant_impl = variant.inner.build_try_from_element(
&(Path {
leading_colon: None,
segments: [
PathSegment::from(enum_ident.clone()),
PathSegment::from(ident.clone()),
]
.into_iter()
.collect(),
}
.into()),
&namespace_expr,
residual,
&[attribute_name.as_str()],
)?;
let variant_impl = quote! {
let mut result = #variant_impl;
#validate
Ok(result)
};
if variant.fallback.is_set() {
fallback = Some(quote! {
_ => { #variant_impl },
})
}
iter = quote! {
#iter
#xml_name => { #variant_impl },
};
}
let fallback = fallback.unwrap_or_else(|| quote! {
_ => Err(::xso::error::Error::ParseError(concat!("This is not a ", stringify!(#enum_ident), " element."))),
});
let on_missing = format!(
"Required discriminator attribute '{}' on enum {} element missing.",
attribute_name, enum_ident,
);
let normalize = match self.normalize_with {
Some(ref normalize_with) => quote! {
let attr_value = attr_value.map(|value| #normalize_with(value));
let attr_value = attr_value.as_ref().map(|value| ::std::borrow::Borrow::<str>::borrow(value));
},
None => quote! {},
};
Ok(quote! {
if #residual.is(#xml_name, #xml_namespace) {
let attr_value = #residual.attr(#attribute_name);
#normalize
match attr_value {
Some(v) => match v {
#iter
#fallback
}
None => Err(::xso::error::Error::ParseError(#on_missing)),
}
} else {
Err(::xso::error::Error::TypeMismatch("", "", #residual))
}
})
}
/// Construct a token stream which contains the arms of a `match`
/// expression dissecting the enum and building `minidom::Element` objects
/// for each variant.
///
/// `ty_ident` must be the identifier of the enum's type.
fn build_into_element(&self, ty_ident: &Ident) -> Result<TokenStream> {
let xml_namespace = &self.namespace;
let xml_name = &self.name;
let attribute_name = &self.attribute_name;
let namespace_expr = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: xml_namespace.clone(),
});
let builder = Ident::new("builder", Span::call_site());
let mut matchers = quote! {};
for variant in self.variants.iter() {
let attribute_value = &variant.value;
let path = Path {
leading_colon: None,
segments: [
PathSegment::from(ty_ident.clone()),
PathSegment::from(variant.ident.clone()),
]
.into_iter()
.collect(),
};
let (orig_names, mapped_names, map_ident) =
build_ident_mapping(variant.inner.iter_members());
let into_element = variant.inner.build_into_element(
&(Path::from(ty_ident.clone()).into()),
&namespace_expr,
&builder,
map_ident,
)?;
matchers = quote! {
#matchers
#path { #( #orig_names: #mapped_names ),* } => {
let #builder = ::xso::exports::minidom::Element::builder(
#xml_name,
#namespace_expr,
).attr(#attribute_name, #attribute_value);
let #builder = #into_element;
#builder.build()
},
};
}
Ok(matchers)
}
}
/// An enum where each variant has completely independent matching.
#[derive(Debug)]
struct Dynamic {
/// Variants of the enum.
variants: Vec<DynamicVariant>,
}
impl Dynamic {
/// Construct a dynamic enum from an iterable of variants.
fn new<'x, I: Iterator<Item = &'x Variant>>(input: I) -> Result<Self> {
let mut variants = Vec::with_capacity(input.size_hint().1.unwrap_or(0));
for variant in input {
let variant = DynamicVariant::new(variant)?;
variants.push(variant);
}
Ok(Self { variants })
}
/// Construct an expression which consumes the `minidom::Element` at
/// `residual` and returns a `Result<T, Error>`.
///
/// - `enum_ident` must be the identifier of the enum's type.
/// - `validate` must be a statement which takes a mutable reference to
/// the identifier `result` and `return`'s with an error if it is not
/// acceptable.
/// - `residual` must be the identifier at which the element is found.
fn build_try_from_element(
&self,
enum_ident: &Ident,
validate: Stmt,
residual: &Ident,
) -> Result<TokenStream> {
let mut matchers = quote! {};
for variant in self.variants.iter() {
let ident = &variant.ident;
let try_from_impl = variant.inner.build_try_from_element(
&(Path {
leading_colon: None,
segments: [
PathSegment::from(enum_ident.clone()),
PathSegment::from(ident.clone()),
]
.into_iter()
.collect(),
}
.into()),
residual,
)?;
matchers = quote! {
#matchers
let mut #residual = match #try_from_impl {
Ok(mut result) => {
#validate
return Ok(result);
},
Err(#residual) => #residual,
};
}
}
Ok(quote! {
{
#matchers
Err(::xso::error::Error::TypeMismatch("", "", #residual))
}
})
}
/// Construct a token stream which contains the arms of a `match`
/// expression dissecting the enum and building `minidom::Element` objects
/// for each variant.
///
/// `ty_ident` must be the identifier of the enum's type.
fn build_into_element(&self, enum_ident: &Ident) -> Result<TokenStream> {
let mut matchers = quote! {};
for variant in self.variants.iter() {
let ident = &variant.ident;
let path = Path {
leading_colon: None,
segments: [
PathSegment::from(enum_ident.clone()),
PathSegment::from(ident.clone()),
]
.into_iter()
.collect(),
};
let (orig_names, mapped_names, map_ident) =
build_ident_mapping(variant.inner.iter_members());
let into_impl = variant
.inner
.build_into_element(&(path.into()), map_ident)?;
matchers = quote! {
#matchers
#enum_ident::#ident { #( #orig_names: #mapped_names ),* } => { #into_impl },
}
}
Ok(matchers)
}
}
/// Inner part of [`EnumDef`], supporting the different styles of
/// enumerations.
#[derive(Debug)]
enum EnumInner {
/// Enum item where the variants switch on the XML element's name.
XmlNameSwitched(XmlNameSwitched),
/// Enum item where the variants switch on the value of an attribute on
/// the XML element.
XmlAttributeSwitched(XmlAttributeSwitched),
/// Enum item which has no matcher on the enum itself, where each variant
/// may be an entirely different XML element.
Dynamic(Dynamic),
}
impl EnumInner {
/// Construct an expression which consumes the `minidom::Element` at
/// `residual` and returns a `Result<T, Error>`.
///
/// - `enum_ident` must be the identifier of the enum's type.
/// - `validate` must be a statement which takes a mutable reference to
/// the identifier `result` and `return`'s with an error if it is not
/// acceptable.
/// - `residual` must be the identifier at which the element is found.
fn build_try_from_element(
&self,
enum_ident: &Ident,
validate: Stmt,
residual: &Ident,
) -> Result<TokenStream> {
match self {
Self::XmlNameSwitched(inner) => {
inner.build_try_from_element(enum_ident, validate, residual)
}
Self::XmlAttributeSwitched(inner) => {
inner.build_try_from_element(enum_ident, validate, residual)
}
Self::Dynamic(inner) => inner.build_try_from_element(enum_ident, validate, residual),
}
}
/// Construct a token stream which contains the arms of a `match`
/// expression dissecting the enum and building `minidom::Element` objects
/// for each variant.
///
/// `ty_ident` must be the identifier of the enum's type.
fn build_into_element(&self, ty_ident: &Ident) -> Result<TokenStream> {
match self {
Self::XmlNameSwitched(inner) => inner.build_into_element(ty_ident),
Self::XmlAttributeSwitched(inner) => inner.build_into_element(ty_ident),
Self::Dynamic(inner) => inner.build_into_element(ty_ident),
}
}
}
/// Represent an enum.
#[derive(Debug)]
pub(crate) struct EnumDef {
/// The `validate` value, if set on the enum.
///
/// This is called after the enum has been otherwise parsed successfully
/// with the enum value as mutable reference as only argument. It is
/// expected to return `Result<(), Error>`, the `Err(..)` variant of which
/// is forwarded correctly.
validate: Option<Path>,
/// The `prepare` value, if set on the enum.
///
/// This is called before the enum will be converted back into an XML
/// element with the enum value as mutable reference as only argument.
prepare: Option<Path>,
/// The actual contents of the enum.
inner: EnumInner,
/// The `debug` flag, if set on the enum.
#[cfg_attr(not(feature = "debug"), allow(dead_code))]
debug: Flag,
}
impl EnumDef {
/// Construct a new enum from its `#[xml(..)]` attribute and the variants.
fn new<'x, I: Iterator<Item = &'x Variant>>(
meta: Option<XmlCompoundMeta>,
input: I,
) -> Result<Self> {
let meta = match meta {
Some(v) => v,
None => XmlCompoundMeta::empty(Span::call_site()),
};
let prepare = meta.prepare;
let validate = meta.validate;
let debug = meta.debug;
if let Flag::Present(fallback) = meta.fallback {
return Err(syn::Error::new(
fallback,
"`fallback` is not allowed on enums (only on enum variants)",
));
}
if let Flag::Present(transparent) = meta.transparent {
return Err(syn::Error::new(
transparent,
"`transparent` cannot be set set on enums (only on enum variants)",
));
}
if let Some(value) = meta.value {
return Err(syn::Error::new_spanned(
value,
"`value` is not allowed on enums",
));
}
let namespace = match meta.namespace {
None => {
// no namespace -> must be dynamic variant. ensure the other
// stuff isn't there.
if let Some(name) = meta.name {
return Err(syn::Error::new_spanned(
name,
"`name` cannot be set without `namespace` or on dynamic enums",
));
}
if let Flag::Present(exhaustive) = meta.exhaustive {
return Err(syn::Error::new(
exhaustive,
"`transparent` cannot be set set on dynamic enums",
));
}
if let Some(normalize_with) = meta.normalize_with {
return Err(syn::Error::new_spanned(
normalize_with,
"`normalize_with` option is only allowed on attribute value switched enums",
));
};
return Ok(Self {
validate,
prepare,
debug,
inner: EnumInner::Dynamic(Dynamic::new(input)?),
});
}
Some(NamespaceRef::Static(ns)) => ns,
Some(NamespaceRef::Dyn(ns)) => {
return Err(syn::Error::new_spanned(
ns,
"`#[xml(namespace = dyn)]` cannot be used on enums.",
))
}
Some(NamespaceRef::Super(ns)) => {
return Err(syn::Error::new_spanned(
ns,
"`#[xml(namespace = super)]` cannot be used on enums.",
))
}
};
let exhaustive = meta.exhaustive;
let name = match meta.name {
None => {
if let Some(normalize_with) = meta.normalize_with {
return Err(syn::Error::new_spanned(
normalize_with,
"`normalize_with` option is only allowed on attribute value switched enums",
));
};
return Ok(Self {
prepare,
validate,
debug,
inner: EnumInner::XmlNameSwitched(XmlNameSwitched::new(
exhaustive, namespace, input,
)?),
});
}
Some(name) => name,
};
let Some(attribute_name) = meta.attribute else {
return Err(syn::Error::new(
meta.span,
"`attribute` option with the name of the XML attribute to match is required for enums matching on attribute value",
));
};
Ok(Self {
prepare,
validate,
debug,
inner: EnumInner::XmlAttributeSwitched(XmlAttributeSwitched::new(
exhaustive,
namespace,
name.into(),
attribute_name,
meta.normalize_with,
input,
)?),
})
}
}
impl ItemDef for EnumDef {
fn build_try_from_element(
&self,
item_name: &ParentRef,
residual: &Ident,
) -> Result<TokenStream> {
let Some(ty_ident) = item_name.try_as_ident() else {
panic!("EnumDef::build_try_from_element cannot be called with non-ident ParentRef");
};
let validate = build_validate(self.validate.as_ref());
let result = self
.inner
.build_try_from_element(ty_ident, validate, residual)?;
#[cfg(feature = "debug")]
if self.debug.is_set() {
println!("{}", result);
}
Ok(result)
}
fn build_into_element(
&self,
item_name: &ParentRef,
value_ident: &Ident,
) -> Result<TokenStream> {
let Some(ty_ident) = item_name.try_as_ident() else {
panic!("EnumDef::build_try_from_element cannot be called with non-ident ParentRef");
};
let prepare = build_prepare(self.prepare.as_ref(), value_ident);
let matchers = self.inner.build_into_element(ty_ident)?;
let result = quote! {
{
#prepare
match #value_ident {
#matchers
}
}
};
#[cfg(feature = "debug")]
if self.debug.is_set() {
println!("{}", result);
}
Ok(result)
}
fn build_dyn_namespace(&self) -> Result<TokenStream> {
Err(Error::new(
Span::call_site(),
"DynNamespace cannot be derived on enums (yet)",
))
}
}
pub(crate) fn parse_enum(item: &syn::ItemEnum) -> Result<Box<dyn ItemDef>> {
let mut meta = XmlCompoundMeta::try_parse_from_attributes(&item.attrs)?;
let wrapped_with = meta.as_mut().map(|x| (x.wrapped_with.take(), x.span));
let mut def = Box::new(EnumDef::new(meta, item.variants.iter())?) as Box<dyn ItemDef>;
if let Some((Some(wrapped_with), span)) = wrapped_with {
def = crate::wrapped::wrap(&span, wrapped_with, &item.ident, def)?;
}
Ok(def)
}