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 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
/*!
# Data structures and processing for `#[xml(..)]` attributes
This module is responsible for processing the syntax trees of the `#[xml(..)]`
attributes fields, enums, enum variants, and structs into more friendly
data structures.
However, it is not yet concerned as much with semantic validation: a lot of
invalid combinations can and will be represented with the data structures from
this module. The downstream consumers of these data structures, such as the
structs in the [`crate::field`] module, are responsible for ensuring that the
given combinations make sense and emit compile-time errors if they do not.
*/
use std::fmt;
use std::ops::ControlFlow;
use proc_macro2::{Span, TokenStream};
use quote::ToTokens;
use syn::{spanned::Spanned, *};
/// Helper macro to chain multiple [`MetaParse`] structs in a series.
///
/// This attempts to parse one `option` after the other, each of which must
/// be an expression evaluating to a thing implementing [`MetaParse`]. If any
/// matches, `Ok(())` is returned. If none matches, an error message containing
/// the allowed option names by calling `name()` on the `option` values is
/// returned.
macro_rules! parse_meta {
($meta:ident, $($option:expr,)+) => {
#[allow(unused_assignments)]
{
let meta = $meta;
$(
let meta = match $option.parse_at_meta(meta) {
Ok(ControlFlow::Continue(meta)) => meta,
Ok(ControlFlow::Break(())) => return Ok(()),
Err(e) => return Err(e),
};
)+
let mut error = format!("unsupported option. supported options are: ");
let mut first = true;
$(
error.reserve($option.name().len() + 2);
if !first {
error.push_str(", ");
}
first = false;
error.push_str($option.name());
)+
Err(Error::new_spanned(meta.path, error))
}
}
}
/// Helper trait to parse a value of some kind from a
/// [`syn::meta::ParseNestedMeta`].
///
/// This, combined with the [`parse_meta!`] macro, reduces code duplication
/// in the various parsing functions significantly.
trait MetaParse {
/// The identifier to match against the path of the meta.
fn name(&self) -> &'static str;
/// The actual workhorse: Assuming that the path matches [`Self::name`],
/// parse the data from the meta.
fn force_parse_at_meta<'x>(&mut self, meta: meta::ParseNestedMeta<'x>) -> Result<()>;
/// Test the path against [`Self::name`] and parse the value if the path
/// matches.
///
/// Otherwise, return [`std::ops::ControlFlow::Continue`] with the meta
/// to allow other things to be parsed from it.
fn parse_at_meta<'x>(
&mut self,
meta: meta::ParseNestedMeta<'x>,
) -> Result<ControlFlow<(), meta::ParseNestedMeta<'x>>> {
if !meta.path.is_ident(self.name()) {
return Ok(ControlFlow::Continue(meta));
}
Ok(ControlFlow::Break(self.force_parse_at_meta(meta)?))
}
}
/// Parse a [`Flag`] from a meta.
struct ParseFlag<'a>(&'static str, &'a mut Flag);
impl<'a> MetaParse for ParseFlag<'a> {
fn name(&self) -> &'static str {
self.0
}
fn force_parse_at_meta<'x>(&mut self, meta: meta::ParseNestedMeta<'x>) -> Result<()> {
if self.1.is_set() {
return Err(Error::new_spanned(
meta.path,
format!("flag {} is already set", self.name()),
));
}
*self.1 = Flag::Present(meta.path.span());
Ok(())
}
}
/// Parse a [`FlagOr`] from a meta.
struct ParseFlagOr<'a, T>(&'static str, &'a mut FlagOr<T>);
impl<'a, T: parse::Parse> MetaParse for ParseFlagOr<'a, T> {
fn name(&self) -> &'static str {
self.0
}
fn force_parse_at_meta<'x>(&mut self, meta: meta::ParseNestedMeta<'x>) -> Result<()> {
if self.1.is_set() {
return Err(Error::new_spanned(
meta.path,
format!("flag {} is already set", self.name()),
));
}
if meta.input.peek(Token![=]) {
*self.1 = FlagOr::Value {
span: meta.path.span(),
value: meta.value()?.parse()?,
};
} else {
*self.1 = FlagOr::Present(meta.path.span());
}
Ok(())
}
}
/// Parse any parseable value from a meta.
struct ParseValue<'a, T: parse::Parse>(&'static str, &'a mut Option<T>);
impl<'a, T: parse::Parse> MetaParse for ParseValue<'a, T> {
fn name(&self) -> &'static str {
self.0
}
fn force_parse_at_meta<'x>(&mut self, meta: meta::ParseNestedMeta<'x>) -> Result<()> {
if self.1.is_some() {
return Err(Error::new_spanned(
meta.path,
format!("duplicate {} option", self.name()),
));
}
*self.1 = Some(meta.value()?.parse()?);
Ok(())
}
}
/// Parse a `NodeFilterMeta` from a meta.
struct ParseNodeFilter<'a>(&'static str, &'a mut Option<NodeFilterMeta>);
impl<'a> MetaParse for ParseNodeFilter<'a> {
fn name(&self) -> &'static str {
self.0
}
fn force_parse_at_meta<'x>(&mut self, meta: meta::ParseNestedMeta<'x>) -> Result<()> {
if self.1.is_some() {
return Err(Error::new_spanned(
meta.path,
format!("duplicate {} option", self.name()),
));
}
*self.1 = Some(NodeFilterMeta::parse_from_meta(meta)?);
Ok(())
}
}
/// Parse a `Vec<Box<XmlFieldMeta>>` from a meta.
struct ParseExtracts<'a>(&'a mut Vec<Box<XmlFieldMeta>>);
impl<'a> MetaParse for ParseExtracts<'a> {
fn name(&self) -> &'static str {
"extract"
}
fn force_parse_at_meta<'x>(&mut self, meta: meta::ParseNestedMeta<'x>) -> Result<()> {
meta.parse_nested_meta(|meta| {
self.0.push(Box::new(XmlFieldMeta::parse_from_meta(meta)?));
Ok(())
})
}
}
/// Represents a boolean flag from a `#[xml(..)]` attribute meta.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Flag {
/// The flag is not set.
Absent,
/// The flag was set.
Present(
/// The span of the syntax element which enabled the flag.
///
/// This is used to generate useful error messages by pointing at the
/// specific place the flag was activated.
Span,
),
}
impl Flag {
/// Return true if the flag is set, false otherwise.
pub fn is_set(&self) -> bool {
match self {
Self::Absent => false,
Self::Present(_) => true,
}
}
/// Basically [`Option::take`], but for [`Flag`].
pub fn take(&mut self) -> Self {
let mut tmp = Flag::Absent;
std::mem::swap(&mut tmp, self);
tmp
}
}
impl<T: Spanned> From<T> for Flag {
fn from(other: T) -> Flag {
Flag::Present(other.span())
}
}
/// A flag with an optional value.
#[derive(Clone, Debug)]
pub(crate) enum FlagOr<T> {
/// The flag is not set.
Absent,
/// The flag was set.
Present(
/// The span of the syntax element which enabled the flag.
///
/// This is used to generate useful error messages by pointing at the
/// specific place the flag was activated.
Span,
),
/// A value was assigned.
Value {
/// The span of the left hand side of the assignment.
span: Span,
/// The actual value.
value: T,
},
}
impl<T> FlagOr<T> {
/// Return true if the flag is set, false otherwise.
pub fn is_set(&self) -> bool {
match self {
Self::Absent => false,
Self::Present(_) => true,
Self::Value { .. } => true,
}
}
/// Obtain the span of the path setting the flag or value.
pub fn span(&self) -> Option<Span> {
match self {
Self::Absent => None,
Self::Present(ref span) => Some(*span),
Self::Value { ref span, .. } => Some(*span),
}
}
/// Obtain the span of the path setting the flag or value.
pub fn into_span(self) -> Option<Span> {
match self {
Self::Absent => None,
Self::Present(span) => Some(span),
Self::Value { span, .. } => Some(span),
}
}
}
/// Type alias for a XML namespace setting.
///
/// This may in the future be replaced by an enum supporting both `Path` and
/// `LitStr`.
pub(crate) type StaticNamespace = Path;
/// Value of a `#[xml(namespace = ..)]` attribute.
///
/// XML namespaces can be configured in different ways, which are
/// distinguished in this enum.
#[derive(Debug)]
pub(crate) enum NamespaceRef {
/// A dynamic namespace, expressed as `#[xml(namespace = dyn)]`.
///
/// See [`crate::structs::StructNamespace::Dyn`] for details.
Dyn(
/// The original `dyn` token for better error messages.
Token![dyn],
),
/// Refer to the parent struct's namespace, expressed as
/// `#[xml(namespace = super)]`.
Super(
/// The original `super` token for better error messages.
Token![super],
),
/// A static namespace identified by a static string, expressed as
/// `#[xml(namespace = crate::ns::FOO)]` or similar.
Static(StaticNamespace),
}
impl parse::Parse for NamespaceRef {
fn parse(input: parse::ParseStream<'_>) -> Result<Self> {
if input.peek(Token![dyn]) {
let ns = input.parse()?;
Ok(Self::Dyn(ns))
} else if input.peek(Token![super]) && !input.peek2(Token![::]) {
let ns = input.parse()?;
Ok(Self::Super(ns))
} else {
let ns = input.parse()?;
Ok(Self::Static(ns))
}
}
}
impl ToTokens for NamespaceRef {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Dyn(ns) => ns.to_tokens(tokens),
Self::Super(ns) => ns.to_tokens(tokens),
Self::Static(ns) => ns.to_tokens(tokens),
}
}
fn into_token_stream(self) -> TokenStream {
match self {
Self::Dyn(ns) => ns.into_token_stream(),
Self::Super(ns) => ns.into_token_stream(),
Self::Static(ns) => ns.into_token_stream(),
}
}
}
/// Type alias for a XML name setting.
///
/// This may in the future be replaced by an enum supporting both `Path` and
/// `LitStr`.
pub(crate) type NameRef = LitStr;
/// An XML name.
///
/// This enum, unlike when passing around the XML name as a string, preserves
/// the original tokens, which is useful for better error messages.
#[derive(Debug)]
pub(crate) enum Name {
/// Represented as a string literal.
Lit(LitStr),
/// Represented as an identifier, e.g. when it is derived from an
/// `#[xml(attribute)]` field's identifier.
Ident(Ident),
}
impl From<LitStr> for Name {
fn from(other: LitStr) -> Self {
Self::Lit(other)
}
}
impl From<Ident> for Name {
fn from(other: Ident) -> Self {
Self::Ident(other)
}
}
impl From<Name> for LitStr {
fn from(other: Name) -> Self {
match other {
Name::Lit(v) => v,
Name::Ident(v) => LitStr::new(&v.to_string(), v.span()),
}
}
}
impl From<&Name> for LitStr {
fn from(other: &Name) -> Self {
match other {
Name::Lit(v) => v.clone(),
Name::Ident(v) => LitStr::new(&v.to_string(), v.span()),
}
}
}
impl fmt::Display for Name {
fn fmt<'f>(&self, f: &'f mut fmt::Formatter) -> fmt::Result {
match self {
Self::Lit(s) => f.write_str(&s.value()),
Self::Ident(s) => s.fmt(f),
}
}
}
impl ToTokens for Name {
fn to_tokens(&self, tokens: &mut TokenStream) {
let s: LitStr = self.into();
s.to_tokens(tokens)
}
fn into_token_stream(self) -> TokenStream {
let s: LitStr = self.into();
s.into_token_stream()
}
}
/// Struct containing namespace and name matchers.
#[derive(Default, Debug)]
pub(crate) struct NodeFilterMeta {
/// The value of the `namespace` option.
pub(crate) namespace: Option<NamespaceRef>,
/// The value of the `name` option.
pub(crate) name: Option<NameRef>,
}
impl NodeFilterMeta {
/// Parse the struct's contents from a potenially nested meta.
///
/// This supports three syntaxes, assuming that `foo` is the meta we're
/// at:
///
/// - `#[xml(.., foo, ..)]` (no value at all): All pieces of the returned
/// struct are `None`.
///
/// - `#[xml(.., foo(..), ..)]`, where `foo` may contain the keys
/// `namespace` and `name`, specifying the values of the struct
/// respectively.
fn parse_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
if meta.input.peek(token::Paren) {
let mut name: Option<NameRef> = None;
let mut namespace: Option<NamespaceRef> = None;
meta.parse_nested_meta(|meta| {
parse_meta!(
meta,
ParseValue("name", &mut name),
ParseValue("namespace", &mut namespace),
)
})?;
Ok(Self { namespace, name })
} else {
Ok(Self::default())
}
}
}
/// Contents of an `#[xml(..)]` attribute on a struct, enum variant, or enum.
///
/// This is the counterpart to [`XmlFieldMeta`].
#[derive(Debug)]
pub(crate) struct XmlCompoundMeta {
/// The span of the `#[xml(..)]` meta from which this was parsed.
///
/// This is useful for error messages.
pub(crate) span: Span,
/// The value assigned to `namespace` inside `#[xml(..)]`, if any.
pub(crate) namespace: Option<NamespaceRef>,
/// The value assigned to `name` inside `#[xml(..)]`, if any.
pub(crate) name: Option<NameRef>,
/// The value assigned to `attribute` inside `#[xml(..)]`, if any.
pub(crate) attribute: Option<LitStr>,
/// The value assigned to `value` inside `#[xml(..)]`, if any.
pub(crate) value: Option<LitStr>,
/// Flag indicating the presence of `fallback` inside `#[xml(..)].
pub(crate) fallback: Flag,
/// Flag indicating the presence of `transparent` inside `#[xml(..)].
pub(crate) transparent: Flag,
/// Flag indicating the presence of `exhaustive` inside `#[xml(..)].
pub(crate) exhaustive: Flag,
/// The value assigned to `validate` inside `#[xml(..)]`, if any.
pub(crate) validate: Option<Path>,
/// The value assigned to `prepare` inside `#[xml(..)]`, if any.
pub(crate) prepare: Option<Path>,
/// The value assigned to `normalize_with` inside `#[xml(..)]`, if any.
pub(crate) normalize_with: Option<Path>,
/// Flag indicating the presence of `debug` inside `#[xml(..)]`
pub(crate) debug: Flag,
/// The options set inside `element`, if any.
pub(crate) element: Option<NodeFilterMeta>,
/// The options set inside `wrapped_with(..)`, if any.
pub(crate) wrapped_with: Option<NodeFilterMeta>,
/// Member of the `UnknownChildPolicy` enum to use when handling unknown
/// children.
pub(crate) on_unknown_child: Option<Ident>,
/// Member of the `UnknownAttributePolicy` enum to use when handling
/// unknown attributes.
pub(crate) on_unknown_attribute: Option<Ident>,
}
impl XmlCompoundMeta {
pub(crate) fn empty(span: Span) -> Self {
XmlCompoundMeta {
span,
namespace: None,
name: None,
attribute: None,
value: None,
fallback: Flag::Absent,
transparent: Flag::Absent,
exhaustive: Flag::Absent,
validate: None,
prepare: None,
wrapped_with: None,
normalize_with: None,
debug: Flag::Absent,
element: None,
on_unknown_attribute: None,
on_unknown_child: None,
}
}
/// Parse the meta values from a `#[xml(..)]` attribute.
///
/// Undefined options or options with incompatible values are rejected
/// with an appropriate compile-time error.
fn parse_from_attribute(attr: &Attribute) -> Result<Self> {
let mut name: Option<NameRef> = None;
let mut namespace: Option<NamespaceRef> = None;
let mut attribute: Option<LitStr> = None;
let mut value: Option<LitStr> = None;
let mut fallback = Flag::Absent;
let mut transparent = Flag::Absent;
let mut exhaustive = Flag::Absent;
let mut debug = Flag::Absent;
let mut validate: Option<Path> = None;
let mut prepare: Option<Path> = None;
let mut normalize_with: Option<Path> = None;
let mut element: Option<NodeFilterMeta> = None;
let mut wrapped_with: Option<NodeFilterMeta> = None;
let mut on_unknown_attribute: Option<Ident> = None;
let mut on_unknown_child: Option<Ident> = None;
attr.parse_nested_meta(|meta| {
parse_meta!(
meta,
ParseValue("name", &mut name),
ParseValue("namespace", &mut namespace),
ParseValue("attribute", &mut attribute),
ParseValue("value", &mut value),
ParseFlag("fallback", &mut fallback),
ParseFlag("transparent", &mut transparent),
ParseFlag("exhaustive", &mut exhaustive),
ParseFlag("debug", &mut debug),
ParseValue("validate", &mut validate),
ParseValue("prepare", &mut prepare),
ParseValue("normalize_with", &mut normalize_with),
ParseValue("normalise_with", &mut normalize_with),
ParseNodeFilter("element", &mut element),
ParseNodeFilter("wrapped_with", &mut wrapped_with),
ParseValue("on_unknown_attribute", &mut on_unknown_attribute),
ParseValue("on_unknown_child", &mut on_unknown_child),
)
})?;
Ok(Self {
span: attr.span(),
namespace,
name,
attribute,
value,
fallback,
transparent,
validate,
exhaustive,
prepare,
wrapped_with,
debug,
normalize_with,
element,
on_unknown_child,
on_unknown_attribute,
})
}
/// Search through `attrs` for a single `#[xml(..)]` attribute and parse
/// it.
///
/// Undefined options or options with incompatible values are rejected
/// with an appropriate compile-time error.
///
/// If more than one `#[xml(..)]` attribute is found, an error is
/// emitted.
///
/// If no `#[xml(..)]` attribute is found, `None` is returned.
pub(crate) fn try_parse_from_attributes(attrs: &[Attribute]) -> Result<Option<Self>> {
let mut result: Option<Self> = None;
for attr in attrs {
if !attr.path().is_ident("xml") {
continue;
}
if result.is_some() {
return Err(syn::Error::new_spanned(
attr.path(),
"only one #[xml(..)] per struct or enum variant allowed",
));
}
result = Some(Self::parse_from_attribute(attr)?);
}
Ok(result)
}
/// Search through `attrs` for a single `#[xml(..)]` attribute and parse
/// it.
///
/// Undefined options or options with incompatible values are rejected
/// with an appropriate compile-time error.
///
/// If more than one or no `#[xml(..)]` attribute is found, an error is
/// emitted.
pub(crate) fn parse_from_attributes(attrs: &[Attribute]) -> Result<Self> {
match Self::try_parse_from_attributes(attrs)? {
Some(v) => Ok(v),
None => Err(syn::Error::new(
Span::call_site(),
"#[xml(..)] attribute required on struct or enum variant",
)),
}
}
}
/// Helper struct to parse the tupleof XML namespace, XML name,
/// `default` flag, `type` and `codec` option.
///
/// These three are used in several places.
#[derive(Debug)]
struct AttributeMeta {
/// The value assigned to `namespace` inside a potentially nested
/// `#[xml(..)]`, if any.
namespace: Option<NamespaceRef>,
/// The value assigned to `name` inside a potentially nested
/// `#[xml(..)]`, if any.
name: Option<NameRef>,
/// The presence of the `default` flag a potentially nested `#[xml(..)]`,
/// if any.
default_: FlagOr<Path>,
/// The value assigned to `type` inside a potentially nested
/// `#[xml(..)]`, if any.
ty: Option<Type>,
/// The value assigned to `codec` inside a potentially nested
/// `#[xml(..)]`, if any.
codec: Option<Type>,
}
impl AttributeMeta {
/// Parse the struct's contents from a potenially nested meta.
///
/// This supports three syntaxes, assuming that `foo` is the meta we're
/// at:
///
/// - `#[xml(.., foo, ..)]` (no value at all): All pieces of the returned
/// struct are `None` / `Flag::Absent`.
///
/// - `#[xml(.., foo = "bar", ..)]` (direct assignment): The `name` is set
/// to `"bar"`, the other pieces are `None` / `Flag::Absent`.
///
/// - `#[xml(.., foo(..), ..)]`, where `foo` may contain the keys
/// `namespace`, `name` and `default`, specifying the values of the
/// struct respectively.
fn parse_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
if meta.input.peek(Token![=]) {
let name: LitStr = meta.value()?.parse()?;
Ok(Self {
name: Some(name),
namespace: None,
default_: FlagOr::Absent,
codec: None,
ty: None,
})
} else if meta.input.peek(token::Paren) {
let mut name: Option<NameRef> = None;
let mut namespace: Option<NamespaceRef> = None;
let mut ty: Option<Type> = None;
let mut default_: FlagOr<Path> = FlagOr::Absent;
let mut codec: Option<Type> = None;
meta.parse_nested_meta(|meta| {
parse_meta!(
meta,
ParseValue("name", &mut name),
ParseValue("namespace", &mut namespace),
ParseValue("type", &mut ty),
ParseValue("codec", &mut codec),
ParseFlagOr("default", &mut default_),
)
})?;
Ok(Self {
namespace,
name,
default_,
codec,
ty,
})
} else {
Ok(Self {
namespace: None,
name: None,
default_: FlagOr::Absent,
codec: None,
ty: None,
})
}
}
/// Emit an error with the given message if the type is set
fn reject_type(&self, msg: impl Into<String>) -> Result<()> {
if let Some(ty) = self.ty.as_ref() {
Err(Error::new_spanned(ty, msg.into()))
} else {
Ok(())
}
}
/// Emit an error with the given message if the codec is set
fn reject_codec(&self, msg: impl Into<String>) -> Result<()> {
if let Some(codec) = self.codec.as_ref() {
Err(Error::new_spanned(codec, msg.into()))
} else {
Ok(())
}
}
/// Emit an error with the given message if the codec is set
fn reject_default(&self, msg: impl Into<String>) -> Result<()> {
if let Some(span) = self.default_.span() {
Err(Error::new(span, msg.into()))
} else {
Ok(())
}
}
}
/// Mode for destructured child collection.
#[derive(Debug)]
pub(crate) enum ChildMode {
/// The field represents a single XML child element.
Single,
/// The field represents more than one XML child element.
Collection,
}
/// Contents of an `#[xml(..)]` attribute on a field.
///
/// This is the counterpart to [`XmlCompoundMeta`].
#[derive(Debug)]
pub(crate) enum XmlFieldMeta {
/// Maps the field to an XML attribute.
///
/// Maps to the `#[xml(attribute)]`, `#[xml(attribute = ..)]` and
/// `#[xml(attribute(..))]` Rust syntaxes.
///
/// Gets transformed into [`crate::field::attribute::AttributeField`] in
/// later processing stages.
Attribute {
/// Contents of the `name = ..` option or value assigned to
/// `attribute` in the shorthand syntax.
name: Option<NameRef>,
/// Contents of the `default` flag.
default_: FlagOr<Path>,
/// Contents of the `codec = ..` option.
codec: Option<Type>,
/// Contents of the `type = ..` option.
ty: Option<Type>,
},
/// Maps the field to a destructured XML child element.
///
/// Maps to the `#[xml(child)]`, `#[xml(child(..))]`, `#[xml(children)]`,
/// and `#[xml(children(..)]` Rust syntaxes.
///
/// Gets transformed into [`crate::field::child::ChildField`] in later
/// processing stages.
Child {
/// Distinguishes between `#[xml(child)]` and `#[xml(children)]`
/// variants.
mode: ChildMode,
/// Contents of the `namespace = ..` option.
namespace: Option<NamespaceRef>,
/// Contents of the `name = ..` option.
name: Option<NameRef>,
/// Contents of the `extract(..)` option.
extract: Vec<Box<XmlFieldMeta>>,
/// Contents of the `default` flag.
default_: FlagOr<Path>,
/// Contents of the `skip_if = ..` option.
skip_if: Option<Path>,
/// Contents of the `codec = ..` option.
codec: Option<Path>,
},
/// Maps the field to the compounds' XML element's namespace.
///
/// See also [`crate::structs::StructNamespace::Dyn`].
///
/// Maps to the `#[xml(namespace)]` Rust syntax.
///
/// Gets transformed into [`crate::field::namespace::NamespaceField`] in
/// later processing stages.
Namespace,
/// Maps the field to the text contents of the XML element.
///
/// Maps to the `#[xml(text)]` Rust syntax.
///
/// Gets transformed into [`crate::field::text::TextField`] in later
/// processing stages.
Text {
/// Contents of the `codec = ..` option.
codec: Option<Type>,
/// Contents of the `type = ..` option.
ty: Option<Type>,
},
/// Maps the field to a subset of XML child elements, without
/// destructuring them into Rust structs.
///
/// Maps to the `#[xml(elements)]` and `#[xml(elements(..))]` Rust
/// syntaxes.
///
/// Gets transformed into [`crate::field::element::ElementsField`] in
/// later processing stages.
Elements {
/// Contents of the `namespace = ..` option.
namespace: Option<NamespaceRef>,
/// Contents of the `name = ..` option.
name: Option<NameRef>,
},
/// Maps the field to a single of XML child element, without destructuring
/// it into a Rust struct.
///
/// Maps to the `#[xml(element(..))]` Rust syntax.
///
/// Gets transformed into [`crate::field::element::ElementField`] in
/// later processing stages.
Element {
/// Contents of the `namespace = ..` option.
namespace: Option<NamespaceRef>,
/// Contents of the `name = ..` option.
name: Option<NameRef>,
/// Contents of the `default` flag.
default_: FlagOr<Path>,
},
/// Maps the field to the presence of an empty XML child element.
///
/// Maps to the `#[xml(flag(..))]` Rust syntax.
///
/// Gets transformed into [`crate::field::flag::FlagField`] in later
/// processing stages.
Flag {
/// Contents of the `namespace = ..` option.
namespace: Option<NamespaceRef>,
/// Contents of the `name = ..` option.
name: Option<NameRef>,
},
/// Ignores the field for the purpose of XML processing.
///
/// Maps to the `#[xml(ignore)]` Rust syntax.
///
/// Gets transformed into [`crate::field::Ignore`] in later processing
/// stages.
Ignore,
}
static VALID_FIELD_XML_OPTIONS: &'static str =
"attribute, child, children, namespace, text, elements, element, flag, ignore";
impl XmlFieldMeta {
/// Processes a `#[xml(attribute)]` meta, creating a [`Self::Attribute`]
/// variant.
fn attribute_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let meta = AttributeMeta::parse_from_meta(meta)?;
if let Some(namespace) = meta.namespace {
return Err(Error::new_spanned(
namespace,
"namespaced attributes are not supported yet...",
));
}
Ok(Self::Attribute {
name: meta.name,
default_: meta.default_,
codec: meta.codec,
ty: meta.ty,
})
}
/// Common processing for the `#[xml(child)]` and `#[xml(children)]`
/// metas.
fn child_common_from_meta(
meta: meta::ParseNestedMeta<'_>,
) -> Result<(
Option<NamespaceRef>,
Option<NameRef>,
Vec<Box<XmlFieldMeta>>,
FlagOr<Path>,
Option<Path>,
Option<Path>,
)> {
if meta.input.peek(token::Paren) {
let mut name: Option<NameRef> = None;
let mut namespace: Option<NamespaceRef> = None;
let mut extract: Vec<Box<XmlFieldMeta>> = Vec::new();
let mut skip_if: Option<Path> = None;
let mut default_ = FlagOr::Absent;
let mut codec: Option<Path> = None;
meta.parse_nested_meta(|meta| {
parse_meta!(
meta,
ParseValue("name", &mut name),
ParseValue("namespace", &mut namespace),
ParseExtracts(&mut extract),
ParseFlagOr("default", &mut default_),
ParseValue("skip_if", &mut skip_if),
ParseValue("codec", &mut codec),
)
})?;
Ok((namespace, name, extract, default_, skip_if, codec))
} else {
Ok((None, None, Vec::new(), FlagOr::Absent, None, None))
}
}
/// Processes a `#[xml(child)]` meta, creating a [`Self::Child`]
/// variant with [`ChildMode::Single`].
fn child_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let (namespace, name, extract, default_, skip_if, codec) =
Self::child_common_from_meta(meta)?;
Ok(Self::Child {
mode: ChildMode::Single,
namespace,
name,
extract,
default_,
skip_if,
codec,
})
}
/// Processes a `#[xml(children)]` meta, creating a [`Self::Child`]
/// variant with [`ChildMode::Collection`].
fn children_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let (namespace, name, extract, default_, skip_if, codec) =
Self::child_common_from_meta(meta)?;
if let Some(default_) = default_.into_span() {
return Err(syn::Error::new(default_, "default cannot be used on #[xml(children)] (it is implied, the default is the empty container)"));
}
Ok(Self::Child {
mode: ChildMode::Collection,
namespace,
name,
extract,
default_: FlagOr::Absent,
skip_if,
codec,
})
}
/// Processes a `#[xml(namespace)]` meta, creating a [`Self::Namespace`]
/// variant.
fn namespace_from_meta(_meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
Ok(Self::Namespace)
}
/// Processes a `#[xml(texd)]` meta, creating a [`Self::Text`]
/// variant.
fn text_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let mut codec: Option<Type> = None;
let mut ty: Option<Type> = None;
if meta.input.peek(token::Paren) {
#[rustfmt::skip] // rustfmt transforms the code so that the attribute inside parse_meta! is on an expression which is not allowed
meta.parse_nested_meta(|meta| {
parse_meta!(
meta,
ParseValue("codec", &mut codec),
ParseValue("type", &mut ty),
)
})?;
}
Ok(Self::Text { codec, ty })
}
/// Processes a `#[xml(element)]` meta, creating a [`Self::Element`]
/// variant.
fn element_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let meta = AttributeMeta::parse_from_meta(meta)?;
meta.reject_codec("codec = .. is not allowed on #[xml(element)]")?;
meta.reject_type("type = .. is not allowed on #[xml(element)]")?;
Ok(Self::Element {
name: meta.name,
namespace: meta.namespace,
default_: meta.default_,
})
}
/// Processes a `#[xml(elements)]` meta, creating a [`Self::Elements`]
/// variant.
fn elements_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let meta = AttributeMeta::parse_from_meta(meta)?;
meta.reject_codec("codec = .. is not allowed on #[xml(elements)]")?;
meta.reject_type("type = .. is not allowed on #[xml(elements)]")?;
meta.reject_default("default cannot be used on #[xml(elements)] (it is implied, the default is the empty container)")?;
Ok(Self::Elements {
name: meta.name,
namespace: meta.namespace,
})
}
/// Processes a `#[xml(flag)]` meta, creating a [`Self::Flag`] variant.
fn flag_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
let meta = AttributeMeta::parse_from_meta(meta)?;
meta.reject_type("type = .. is not allowed on #[xml(flag)]")?;
if let Some(span) = meta.default_.into_span() {
return Err(syn::Error::new(
span,
"default cannot be used on #[xml(flag)] (it is implied, the default false)",
));
}
Ok(Self::Flag {
name: meta.name,
namespace: meta.namespace,
})
}
/// Processes a `#[xml(ignore)]` meta, creating a [`Self::Ignore`]
/// variant.
fn ignore_from_meta(_meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
Ok(Self::Ignore)
}
fn parse_from_meta(meta: meta::ParseNestedMeta<'_>) -> Result<Self> {
if meta.path.is_ident("attribute") {
Self::attribute_from_meta(meta)
} else if meta.path.is_ident("child") {
Self::child_from_meta(meta)
} else if meta.path.is_ident("children") {
Self::children_from_meta(meta)
} else if meta.path.is_ident("namespace") {
Self::namespace_from_meta(meta)
} else if meta.path.is_ident("text") {
Self::text_from_meta(meta)
} else if meta.path.is_ident("elements") {
Self::elements_from_meta(meta)
} else if meta.path.is_ident("element") {
Self::element_from_meta(meta)
} else if meta.path.is_ident("flag") {
Self::flag_from_meta(meta)
} else if meta.path.is_ident("ignore") {
Self::ignore_from_meta(meta)
} else {
Err(Error::new_spanned(
meta.path,
format!(
"unsupported field option. supported options: {}.",
VALID_FIELD_XML_OPTIONS
),
))
}
}
/// Parse an `#[xml(..)]` attribute.
///
/// This switches based on the first identifier within the `#[xml(..)]`
/// attribute and generates a struct variant accordingly.
///
/// Only a single nested attribute is allowed; more than one will be
/// rejected with an appropriate compile-time error.
///
/// If no attribute is contained at all, a compile-time error is
/// generated.
///
/// Undefined options or options with incompatible values are rejected
/// with an appropriate compile-time error.
pub(crate) fn parse_from_attribute(attr: &Attribute) -> Result<Self> {
let mut result: Option<Self> = None;
attr.parse_nested_meta(|meta| {
if result.is_some() {
return Err(Error::new_spanned(
meta.path,
"multiple field options are not supported",
));
}
result = Some(Self::parse_from_meta(meta)?);
Ok(())
})?;
if let Some(result) = result {
Ok(result)
} else {
Err(Error::new_spanned(
attr,
format!(
"missing field options. specify at one of {}.",
VALID_FIELD_XML_OPTIONS
),
))
}
}
/// Take the explicit type specification out of this meta and return it,
/// if any.
///
/// This function *does not recurse* into nested `extract(..)` specs.
pub(crate) fn take_type(&mut self) -> Option<Type> {
match self {
XmlFieldMeta::Attribute { ref mut ty, .. } => ty.take(),
XmlFieldMeta::Text { ref mut ty, .. } => ty.take(),
_ => None,
}
}
/// Take the explicit type specification out of this meta and return it,
/// if any.
///
/// This function **does recurse** into nested `extract(..)` specs and
/// returns types for kinds with known type.
pub(crate) fn determine_type(&mut self) -> Option<Type> {
match self {
Self::Attribute { ref mut ty, .. } => ty.take(),
Self::Child {
ref mut extract,
mode: ChildMode::Single,
..
} => {
if extract.len() == 1 {
extract[0].take_type()
} else {
None // cannot be determined from meta alone
}
}
Self::Child {
mode: ChildMode::Collection,
..
} => None, // cannot be determined from meta alone
Self::Namespace => None, // cannot be determined from meta alone
Self::Text { ref mut ty, .. } => ty.take(),
Self::Elements { .. } => Some(
parse_str("::std::vec::Vec<::xso::exports::minidom::Element>")
.expect("cannot construct elements type"),
),
Self::Element { .. } => Some(
parse_str("::xso::exports::minidom::Element")
.expect("cannot construct element type"),
),
Self::Flag { .. } => Some(parse_str("bool").expect("cannot construct element type")),
Self::Ignore => None,
}
}
}