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
//! Infrastructure for parsing fields from child elements while destructuring
//! their contents.
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::*;
use crate::common::{mangle_into_camel_case_name, Scope, ScopeNamespace};
use crate::compound::Compound;
use crate::error_message::{self, ParentRef};
use crate::meta::{Flag, FlagOr, NameRef, NamespaceRef, XmlFieldMeta};
use crate::types::*;
use super::{
ChildMode, Field, FieldDef, FieldFromEventsPart, FieldIntoEventsPart, FieldNamespace,
FieldTempInit, NestedMatcher,
};
/// Definition of a child data extraction.
///
/// This is used to implement fields annotated with
/// `#[xml(child(.., extract(..))]` or `#[xml(children(.., extract(..)))]`.
#[derive(Debug)]
pub(super) struct ExtractDef {
namespace: FieldNamespace,
name: NameRef,
/// Compound which contains the arguments of the `extract(..)` attribute,
/// transformed into a struct with unnamed fields.
///
/// This is used to generate the parsing/serialisation code, by
/// essentially "declaring" a shim struct, as if it were a real Rust
/// struct, and using the result of the parsing process directly for the
/// field on which the `extract(..)` option was used, instead of putting
/// it into a Rust struct.
parts: Compound,
}
impl ExtractDef {
/// Construct an `ExtractDef`.
///
/// The `namespace` and `name` identify the XML element this `ExtractDef`
/// works on, i.e. the child element to match.
///
/// `parts` contains the pieces of data to extract from the child in the
/// order they are extracted.
///
/// Finally, `single_extract_type` should be passed if the extract is used
/// in the context of a `#[xml(child)]` field (i.e. not for a container)
/// and it should then be the type of that field. This allows defaulting
/// the type of the extract's field to that type if it has not been
/// specified explicitly by the user.
fn new(
span: Span,
namespace: FieldNamespace,
name: NameRef,
parts: Vec<Box<XmlFieldMeta>>,
mut single_extract_type: Option<Type>,
) -> Result<Self> {
if parts.len() != 1 {
single_extract_type = None;
}
let parts = Compound::new(
None,
None,
parts.into_iter().enumerate().map(|(i, x)| {
FieldDef::from_extract(span.clone(), *x, i as u32, single_extract_type.take())
}),
)?;
Ok(Self {
namespace,
name,
parts,
})
}
fn build_from_events_builder(
&self,
from_events_ty_ident: &Ident,
output_name: &ParentRef,
) -> Result<(TokenStream, Type)> {
let xml_name = &self.name;
let state_ty_ident = quote::format_ident!("{}State", from_events_ty_ident);
let (test_expr, scope_namespace) = match self.namespace {
FieldNamespace::Static(ref xml_namespace) => (
quote! {
name.0 == #xml_namespace && name.1 == #xml_name
},
ScopeNamespace::Static(xml_namespace),
),
FieldNamespace::Super(_) => (
quote! {
parent_namespace == name.0.as_str() && name.1 == #xml_name
},
ScopeNamespace::Unavailable,
),
};
let output_ty = self.parts.as_tuple_ty();
let builder = self
.parts
.build_from_events_builder(scope_namespace, &state_ty_ident, output_name, "")?
.render(
&Visibility::Inherited,
from_events_ty_ident,
&state_ty_ident,
&output_ty,
None,
)?;
let from_events_ty = ty_from_ident(from_events_ty_ident.clone()).into();
Ok((
quote! {
#builder
impl #from_events_ty_ident {
#[inline(always)]
fn start_extract(name: ::xso::exports::rxml::QName, attrs: ::xso::exports::rxml::AttrMap, parent_namespace: &(impl ::std::cmp::PartialEq<str> + ?::std::marker::Sized)) -> ::std::result::Result<Self, ::xso::FromEventsError> {
if #test_expr {
Self::new(name, attrs)
} else {
::std::result::Result::Err(::xso::FromEventsError::Mismatch {
name,
attrs,
})
}
}
}
},
from_events_ty,
))
}
fn build_into_events_iterator(
&self,
into_events_ty_ident: &Ident,
input_name: &ParentRef,
) -> Result<(TokenStream, Type)> {
let vis = Visibility::Inherited;
let state_ty_ident = quote::format_ident!("{}State", into_events_ty_ident);
let (xml_namespace, scope_namespace) = match self.namespace {
FieldNamespace::Static(ref xml_namespace) => (
quote! { #xml_namespace },
ScopeNamespace::Static(xml_namespace),
),
FieldNamespace::Super(_) => (
quote! { ::xso::IntoXmlText::into_xml_text(parent_namespace.clone()) },
ScopeNamespace::Unavailable,
),
};
let unpacked_ty = self.inner_type();
let (def, destructure, init) = self
.parts
.build_into_events_iterator(scope_namespace, input_name, "", &state_ty_ident, None)?
.render_partial(&vis, &unpacked_ty, &state_ty_ident, into_events_ty_ident)?;
let xml_name = &self.name;
let nfields = self.parts.field_count();
let repack = if nfields == 1 {
quote! { (value,) }
} else {
quote! { value }
};
let into_events_ty = ty_from_ident(into_events_ty_ident.clone()).into();
Ok((
quote! {
#def
impl #state_ty_ident {
#[inline(always)]
fn start_assemble(qname: ::xso::exports::rxml::QName, value: #unpacked_ty) -> ::std::result::Result<Self, ::xso::error::Error> {
let attrs = ::xso::exports::rxml::AttrMap::new();
let #destructure = #repack;
::std::result::Result::Ok(#init)
}
}
impl #into_events_ty_ident {
#[inline(always)]
fn start_assemble(value: #unpacked_ty, parent_namespace: &(impl ::xso::IntoXmlText + ::std::clone::Clone + ?::std::marker::Sized)) -> ::std::result::Result<Self, ::xso::error::Error> {
let qname = (
::xso::exports::rxml::Namespace::try_from(#xml_namespace)?,
::xso::exports::rxml::NcName::try_from(#xml_name)?,
);
#state_ty_ident::start_assemble(qname, value).map(|ok| Self(::std::option::Option::Some(ok)))
}
}
},
into_events_ty,
))
}
fn inner_type(&self) -> Type {
self.parts
.single_type()
.cloned()
.unwrap_or_else(|| self.parts.as_tuple_ty())
}
}
/// A field parsed from an XML child, destructured into a Rust data structure.
///
/// Maps to `#[xml(child)]` and `#[xml(children)]`.
#[derive(Debug)]
pub(crate) struct ChildField {
/// Determines whether one or more matching child elements are expected.
///
/// This is basically the difference between `#[xml(child(..))]` and
/// `#[xml(children(..))]`.
mode: ChildMode,
/// If set, the field's value will be obtained by destructuring the child
/// element using the given [`ExtractDef`], instead of parsing it using
/// `FromXml`.
extract: Option<ExtractDef>,
/// If set, `extract` must be None, the child's type must implement
/// `DynNamespace` and the compound must use `namespace = dyn`.
super_namespace: Flag,
/// If set, the field's value will be generated using
/// [`std::default::Default`] or the given path if no matching child can
/// be found, instead of aborting parsing with an error.
default_: FlagOr<Path>,
/// If set, it must point to a function. That function will be called with
/// an immutable reference to the field's value and must return a boolean.
/// If that boolean is true, the child will not be emitted.
skip_if: Option<Path>,
/// If set, it must point to a type. The `FromXml`/`IntoXml`
/// implementations of that type will be used instead, and the type must
/// implement `ElementCodec<T>`, where `T` is the type of the field.
codec: Option<Path>,
}
impl ChildField {
/// Construct a new `#[xml(child)]` or `#[xml(children)]` field.
///
/// `mode` distinguishes between `#[xml(child(..))]` and
/// `#[xml(children(..))]` fields.
///
/// If the child is going to be extracted, it `namespace` and `name` must
/// identify the target child's XML namespace and name and `extract` must
/// be the extraction parts to process.
///
/// Otherwise, if no extract is intended, `namespace` and `name` must be
/// `None` and `extract` must be empty.
///
/// The `default_` flag stored, see [`Self::default_`] for semantics.
///
/// `field_type` must be the type of the field. It is used to configure
/// the extract correctly, if it is specified and the mode is single.
///
/// `attr_span` is used for emitting error messages when no better span
/// can be constructed. This should point at the `#[xml(..)]` meta of the
/// field or another closely-related object.
pub(crate) fn new(
attr_span: &Span,
mode: ChildMode,
namespace: Option<NamespaceRef>,
name: Option<NameRef>,
extract: Vec<Box<XmlFieldMeta>>,
default_: FlagOr<Path>,
skip_if: Option<Path>,
codec: Option<Path>,
field_type: &Type,
) -> Result<Self> {
if extract.len() > 0 {
let namespace = match namespace {
None => {
return Err(Error::new(
attr_span.clone(),
"namespace must be specified on extracted fields",
))
}
Some(NamespaceRef::Static(ns)) => FieldNamespace::Static(ns),
Some(NamespaceRef::Dyn(ns)) => {
return Err(Error::new_spanned(
ns,
"extracted fields cannot use dynamic namespaces",
))
}
Some(NamespaceRef::Super(ns)) => FieldNamespace::Super(ns),
};
let Some(name) = name else {
return Err(Error::new(
attr_span.clone(),
"name must be specified on extracted fields",
));
};
if let Some(codec) = codec {
return Err(Error::new_spanned(
codec,
"codec = .. cannot be combined with extract(..)",
));
}
let single_extract_type = match mode {
ChildMode::Single => {
if extract.len() > 1 {
return Err(Error::new(
attr_span.clone(),
"extracting multiple texts from children is only on collection fields",
));
};
Some(field_type.clone())
}
ChildMode::Collection => None,
};
Ok(Self {
mode,
extract: Some(ExtractDef::new(
attr_span.clone(),
namespace,
name.into(),
extract,
single_extract_type,
)?),
skip_if,
default_,
super_namespace: Flag::Absent,
codec: None,
})
} else {
let super_namespace = match namespace {
None => Flag::Absent,
Some(NamespaceRef::Super(ns)) => Flag::Present(ns.span),
Some(namespace) => {
return Err(Error::new_spanned(
namespace,
"namespace declaration not allowed on non-extracted child fields",
));
}
};
if let Some(name) = name {
return Err(Error::new_spanned(
name,
"name declaration not allowed on non-extracted child fields",
));
}
Ok(Self {
mode,
extract: None,
default_,
skip_if,
super_namespace,
codec,
})
}
}
}
impl Field for ChildField {
fn build_from_events_builder(
&self,
scope: &Scope,
container_name: &ParentRef,
tempname: Ident,
member: &Member,
ty: &Type,
) -> Result<FieldFromEventsPart> {
let Scope {
ref start_ev_qname,
ref start_ev_attrs,
ref substate_result,
ref namespace_access,
ref type_prefix,
..
} = scope;
let access = scope.access_field(member);
let ns_test = match self.super_namespace {
Flag::Absent => quote! {
::std::result::Result::Ok((#start_ev_qname, #start_ev_attrs))
},
Flag::Present(_) => quote! {
{
if #namespace_access == #start_ev_qname.0.as_str() {
::std::result::Result::Ok((#start_ev_qname, #start_ev_attrs))
} else {
::std::result::Result::Err(::xso::FromEventsError::Mismatch { name: #start_ev_qname, attrs: #start_ev_attrs })
}
}
},
};
let ty_default = default_fn(ty.clone());
let item_ty = match self.mode {
ChildMode::Single => ty.clone(),
ChildMode::Collection => into_iterator_item_ty(ty.clone()),
};
let (extra_defs, builder, selector, collector) = match self.extract {
Some(ref extract) => {
let from_events_ty_ident = quote::format_ident!(
"{}Member{}FromEvents",
type_prefix,
mangle_into_camel_case_name(tempname.clone(), "")
);
let (extra_defs, from_events_ty) = extract.build_from_events_builder(
&from_events_ty_ident,
&container_name.child(member.clone()),
)?;
let repack = if extract.parts.field_count() == 1 {
quote! {
#substate_result.0.into()
}
} else {
quote! {
#substate_result
}
};
(
extra_defs,
from_events_ty,
quote! { #from_events_ty_ident::start_extract(#start_ev_qname, #start_ev_attrs, #namespace_access) },
repack,
)
}
None => {
let (codec_ty, decoded) = match self.codec {
Some(ref ty) => {
let codec_ty = Type::Path(TypePath {
qself: None,
path: ty.clone(),
});
let decode = element_codec_decode_fn(codec_ty.clone(), item_ty.clone());
(codec_ty, quote! { #decode(#substate_result)? })
}
None => (item_ty.clone(), substate_result.to_token_stream()),
};
let ty_from_events_builder = from_xml_builder_ty(codec_ty.clone());
let codec_ty_from_events = from_events_fn(codec_ty.clone());
(
quote! {},
ty_from_events_builder,
quote! {
#ns_test.and_then(|(#start_ev_qname, #start_ev_attrs)| #codec_ty_from_events(#start_ev_qname, #start_ev_attrs))
},
decoded,
)
}
};
match self.mode {
ChildMode::Single => {
let missingerr = error_message::on_missing_child(container_name, &member);
let duperr = error_message::on_duplicate_child(container_name, &member);
let on_missing = match self.default_ {
FlagOr::Absent => {
quote! {
return Err(::xso::error::Error::ParseError(#missingerr));
}
}
FlagOr::Present(_) => {
quote! {
#ty_default()
}
}
FlagOr::Value { ref value, .. } => {
quote! {
#value()
}
}
};
Ok(FieldFromEventsPart::Nested {
extra_defs,
temp: FieldTempInit {
ty: option_ty(ty.clone()),
init: quote! { ::std::option::Option::None },
},
matcher: NestedMatcher::Inline(quote! {
#selector.and_then(|ok| {
if #access.is_some() {
::std::result::Result::Err(::xso::FromEventsError::Invalid(::xso::error::Error::ParseError(#duperr)))
} else {
::std::result::Result::Ok(ok)
}
})
}),
builder,
collect: quote! {
#access = ::std::option::Option::Some(#collector);
},
finish: quote! {
if let ::std::option::Option::Some(v) = #access {
v
} else {
#on_missing
}
},
})
}
ChildMode::Collection => {
let ty_try_extend = try_extend_fn(ty.clone(), item_ty.clone());
Ok(FieldFromEventsPart::Nested {
extra_defs,
temp: FieldTempInit {
ty: ty.clone(),
init: quote! { #ty_default() },
},
matcher: NestedMatcher::Inline(selector),
builder,
collect: quote! {
#ty_try_extend(&mut #access, [#collector])?;
},
finish: quote! { #access },
})
}
}
}
fn build_set_namespace(&self, input: &Ident, ty: &Type, access: Expr) -> Result<TokenStream> {
match self.mode {
ChildMode::Single => match self.extract {
Some(_) => Ok(quote! {}),
None => match self.super_namespace {
Flag::Absent => Ok(quote! {}),
Flag::Present(_) => {
let method = dyn_namespace_set_fn(ty.clone());
Ok(quote! {
#method(&mut #access, #input.clone());
})
}
},
},
_ => Ok(quote! {}),
}
}
fn build_into_events_iterator(
&self,
scope: &Scope,
container_name: &ParentRef,
tempname: Ident,
member: &Member,
ty: &Type,
) -> Result<FieldIntoEventsPart> {
let Scope {
ref namespace_local,
ref type_prefix,
..
} = scope;
match self.mode {
ChildMode::Single => {
let skip_map = match self.skip_if {
Some(ref callable) => quote! {
#callable(&#tempname)
},
None => quote! { false },
};
let emitter = quote! {
match #tempname.as_mut().and_then(|x| x.next()) {
::std::option::Option::Some(::std::result::Result::Ok(ev)) => ::std::option::Option::Some(ev),
::std::option::Option::Some(::std::result::Result::Err(e)) => return ::std::result::Result::Err(e),
::std::option::Option::None => ::std::option::Option::None,
}
};
match self.extract {
Some(ref extract) => {
let into_events_ty_ident = quote::format_ident!(
"{}Member{}IntoEvents",
type_prefix,
mangle_into_camel_case_name(tempname.clone(), "")
);
let inner_ty = extract.inner_type();
let (extra_defs, into_events_ty) = extract.build_into_events_iterator(
&into_events_ty_ident,
&container_name.child(member.clone()),
)?;
Ok(FieldIntoEventsPart::ContentMut {
extra_defs,
init: quote! {
::std::option::Option::<#inner_ty>::from(#tempname).and_then(|value| {
if #skip_map {
::std::option::Option::None
} else {
::std::option::Option::Some(#into_events_ty_ident::start_assemble(value, &#namespace_local))
}
}).transpose()?
},
emitter,
ty: option_ty(into_events_ty),
})
}
None => {
let field_ty = ty;
let (codec_ty, encoded) = match self.codec {
Some(ref ty) => {
let codec_ty = Type::Path(TypePath {
qself: None,
path: ty.clone(),
});
let encoder =
element_codec_encode_fn(codec_ty.clone(), field_ty.clone());
(codec_ty, quote! { #encoder(#tempname)? })
}
None => (field_ty.clone(), tempname.to_token_stream()),
};
let codec_ty_into_event_iter = into_event_iter_fn(codec_ty.clone());
let codec_ty_into_event_iterator = event_iter_ty(codec_ty.clone());
// TODO: remove option_ty if skip_if is not set
Ok(FieldIntoEventsPart::ContentMut {
extra_defs: TokenStream::default(),
ty: option_ty(codec_ty_into_event_iterator),
init: quote! {
if #skip_map {
::std::option::Option::None
} else {
::std::option::Option::Some(#codec_ty_into_event_iter(#encoded)?)
}
},
emitter,
})
}
}
}
ChildMode::Collection => {
let skip_map = match self.skip_if {
Some(ref callable) => quote! {
#callable(&item)
},
None => quote! { false },
};
let iter_ty = into_iterator_iter_ty(ty.clone());
let (extra_defs, generate_next, into_event_iterator) = match self.extract {
Some(ref extract) => {
let into_events_ty_ident = quote::format_ident!(
"{}Member{}IntoEvents",
type_prefix,
mangle_into_camel_case_name(tempname.clone(), "")
);
let (extra_defs, into_events_ty) = extract.build_into_events_iterator(
&into_events_ty_ident,
&container_name.child(member.clone()),
)?;
(
extra_defs,
quote! {
#into_events_ty_ident::start_assemble(item, &#namespace_local)?
},
into_events_ty,
)
}
None => {
let item_ty = into_iterator_item_ty(ty.clone());
let (codec_ty, encoded) = match self.codec {
Some(ref ty) => {
let codec_ty = Type::Path(TypePath {
qself: None,
path: ty.clone(),
});
let codec_ty_encode =
element_codec_encode_fn(codec_ty.clone(), item_ty);
(codec_ty, quote! { #codec_ty_encode(item)? })
}
None => (item_ty.clone(), quote! { item }),
};
let codec_ty_into_event_iter = into_event_iter_fn(codec_ty.clone());
let codec_ty_into_event_iterator = event_iter_ty(codec_ty.clone());
(
TokenStream::default(),
quote! {
#codec_ty_into_event_iter(#encoded)?
},
codec_ty_into_event_iterator,
)
}
};
let state_ty = Type::Tuple(TypeTuple {
paren_token: syn::token::Paren::default(),
elems: [iter_ty, option_ty(into_event_iterator)]
.into_iter()
.collect(),
});
Ok(FieldIntoEventsPart::ContentMut {
extra_defs,
ty: state_ty,
init: quote! {
(#tempname.into_iter(), None)
},
emitter: quote! {
loop {
if let ::std::option::Option::Some(current) = #tempname.1.as_mut() {
if let ::std::option::Option::Some(item) = current.next() {
break ::std::option::Option::Some(item?);
}
}
if let ::std::option::Option::Some(item) = #tempname.0.next() {
if !#skip_map {
#tempname.1 = ::std::option::Option::Some(#generate_next);
}
} else {
break ::std::option::Option::None;
}
}
},
})
}
}
}
}