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
/*!
Helpers used both for enums and structs.
*/
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{spanned::Spanned, *};
use crate::error_message::ParentRef;
/// Build a statement calling the validator function at `validate`, if any.
///
/// This assumes that the argument for `validate` is called `result`.
pub(crate) fn build_validate(validate: Option<&Path>) -> Stmt {
syn::parse2(if let Some(validate) = validate {
let span = validate.span();
quote_spanned! {span=>
{ let result: ::std::result::Result<(), ::xso::error::Error> = #validate(&mut result); result?; };
}
} else {
quote! {
{ let _ = &mut result; };
}
})
.expect("failed to build validation code")
}
/// Build a statement calling the preparation function at `prepare`, if any.
///
/// The argument passed to `prepare` is `value_ident`.
pub(crate) fn build_prepare(prepare: Option<&Path>, value_ident: &Ident) -> TokenStream {
if let Some(prepare) = prepare {
let span = prepare.span();
quote_spanned! {span=>
{ let _: () = #prepare(&mut #value_ident); };
}
} else {
quote! {
{ let _ = &mut #value_ident; };
}
}
}
/// Parts necessary to construct a `::xso::FromXml` implementation.
pub(crate) struct FromEventsParts {
/// Additional items necessary for the implementation.
pub(crate) struct_def: TokenStream,
/// The body of the `::xso::FromXml::from_events` function.
pub(crate) from_events_body: TokenStream,
/// The name of the type which is the `::xso::FromXml::Builder`.
pub(crate) builder_ty_ident: Ident,
}
/// Parts necessary to construct a `::xso::IntoXml` implementation.
pub(crate) struct IntoEventIterParts {
/// Additional items necessary for the implementation.
pub(crate) struct_def: TokenStream,
/// The body of the `::xso::IntoXml::into_event_iter` function.
pub(crate) into_event_iter_body: TokenStream,
/// The name of the type which is the `::xso::IntoXml::EventIter`.
pub(crate) event_iter_ty_ident: Ident,
}
pub(crate) trait ItemDef: std::fmt::Debug {
/// Construct a token stream containing the entire body of the
/// `impl DynNamespace` block.
///
/// Can only be used on `namespace = dyn` items; any other variants will
/// cause an appropriate compile-time error.
fn build_dyn_namespace(&self) -> Result<TokenStream>;
/// Construct the [`FromEventsParts`] for this type.
///
/// - `vis` must be the desired visibility of the implementation. Note
/// that `vis` must be at least as visible as the visibility of the
/// declaration of `output_ty`.
///
/// - `output_ty`: The type for which to implement the builder.
///
/// - `output_name`: Relative reference to the output type for error
/// message generation purposes.
///
/// - `name_ident`: The identifier at which the `rxml::QName` of the start
/// event is available in [`FromEventsParts::from_events_body`].
///
/// - `attrs_ident`: The identifier at which the `rxml::AttrMap` of the
/// start event is available in [`FromEventsParts::from_events_body`].
fn build_from_events_builder(
&self,
vis: &Visibility,
output_ty: &Type,
output_name: &ParentRef,
name_ident: &Ident,
attrs_ident: &Ident,
) -> Result<FromEventsParts>;
/// Construct the [`FromEventsParts`] for this type.
///
/// - `vis` must be the desired visibility of the implementation. Note
/// that `vis` must be at least as visible as the visibility of the
/// declaration of `input_ty`.
///
/// - `input_ty`: The type for which to implement the iterator.
///
/// - `input_name`: Relative reference to the input type for error
/// message generation purposes.
///
/// - `self_ident`: The identifier at which the value to decompose is
/// availabe in [`IntoEventIterParts::into_event_iter_body`].
fn build_into_events_iterator(
&self,
vis: &Visibility,
input_ty: &Type,
input_name: &ParentRef,
self_ident: &Ident,
) -> Result<IntoEventIterParts>;
/// Return true if the output of the proc macro should be printed to stdout.
fn debug_mode(&self) -> bool;
}
impl<T: ItemDef + ?Sized> ItemDef for Box<T> {
fn build_dyn_namespace(&self) -> Result<TokenStream> {
(**self).build_dyn_namespace()
}
fn build_from_events_builder(
&self,
vis: &Visibility,
output_ty: &Type,
output_name: &ParentRef,
name_ident: &Ident,
attrs_ident: &Ident,
) -> Result<FromEventsParts> {
(**self).build_from_events_builder(vis, output_ty, output_name, name_ident, attrs_ident)
}
fn build_into_events_iterator(
&self,
vis: &Visibility,
input_ty: &Type,
input_name: &ParentRef,
self_ident: &Ident,
) -> Result<IntoEventIterParts> {
(**self).build_into_events_iterator(vis, input_ty, input_name, self_ident)
}
fn debug_mode(&self) -> bool {
(**self).debug_mode()
}
}
/// A partial [`FromEventsStateMachine`] which only covers the builder for a
/// single type.
///
/// See [`FromEventsStateMachine`] for more information on the state machines
/// in general.
pub(crate) struct FromEventsSubmachine {
/// Additional items necessary for the statemachine.
pub(crate) defs: TokenStream,
/// State enumeration member definitions, including the trailing comma.
pub(crate) state_defs: TokenStream,
/// Arms for the `match self { .. }` inside the `advance` function
/// generated for the state enumeration.
pub(crate) advance_match_arms: TokenStream,
/// Initializer expression.
///
/// The exact format required by this expression depends on whether the
/// machine is rendered using [`FromEventsStateMachine::render`] or
/// [`FromEventsStateMachine::render_match`]. See there for requirements.
pub(crate) init: TokenStream,
}
impl FromEventsSubmachine {
/// Create a new partial statemachine parsing a another type
/// transparently.
///
/// The returned statemachine will use `inner_ty`, which must implement
/// `xso::FromEventsBuilder`, to construct a value.
///
/// `state_ident` must be the name of the state enumeration's variant to
/// define. `init` must be an expression valid for
/// [`FromEventsSubmachine::init`] (see there for details).
///
/// `output_cons` must refer to a value constructor which takes a
/// `<#inner_ty as xso::FromEventsBuilder>::Output`. The return type of
/// `output_cons` defines the output type of the generated statemachine.
pub(crate) fn transparent(
inner_ty: &Type,
state_ident: &Ident,
init: TokenStream,
output_cons: &Path,
) -> Self {
let feed = crate::types::feed_fn(inner_ty.clone());
Self {
defs: TokenStream::default(),
state_defs: quote! {
#state_ident(#inner_ty),
},
advance_match_arms: quote! {
Self::#state_ident(mut inner) => {
match #feed(&mut inner, ev) {
::std::result::Result::Ok(::std::option::Option::Some(result)) => {
::std::result::Result::Ok(::std::ops::ControlFlow::Continue(#output_cons(result)))
},
::std::result::Result::Ok(::std::option::Option::None) => ::std::result::Result::Ok(::std::ops::ControlFlow::Break(Self::#state_ident(inner))),
::std::result::Result::Err(e) => ::std::result::Result::Err(e),
}
},
},
init,
}
}
/// Modify the [`FromEventsSubmachine::init`] in-place.
pub(crate) fn augment_init<F: FnOnce(&TokenStream) -> TokenStream>(&mut self, f: F) {
let new_init = f(&self.init);
self.init = new_init;
}
/// Consume self, modify the [`FromEventsSubmachine::init`] and return
/// the result.
pub(crate) fn augmented_init<F: FnOnce(&TokenStream) -> TokenStream>(mut self, f: F) -> Self {
self.augment_init(f);
self
}
/// Render this submachine into a `xso::FromEventsBuilder` implementation.
///
/// Internally, this converts the partial statemachine into a full
/// statemachine and renders that.
///
/// See [`FromEventsStateMachine::render`] for details on the arguments
/// and the return value.
pub(crate) fn render(
self,
vis: &Visibility,
builder_ty_name: &Ident,
state_ty_ident: &Ident,
output_ty: &Type,
validate: Option<Stmt>,
) -> Result<TokenStream> {
let statemachine: FromEventsStateMachine = self.into();
statemachine.render(vis, builder_ty_name, state_ty_ident, output_ty, validate)
}
}
/// Container for a single entrypoint into a [`FromEventsStateMachine`].
pub(crate) struct FromEventsEntryPoint {
pub(crate) init: TokenStream,
}
/**
# State machine to implement `xso::FromEventsBuilder`
This struct represents a state machine consisting of the following parts:
- Extra dependencies ([`Self::defs`])
- States ([`Self::state_defs`])
- Transitions ([`Self::advance_match_arms`])
- Entrypoints ([`Self::variants`])
Such a state machine is best constructed by constructing one or
more [`FromEventsSubmachine`] structs and converting/merging them using
`into()` and [`merge`][`Self::merge`].
A state machine has an output type (corresponding to
`xso::FromEventsBuilder::Output`), which is however only implicitly defined
by the expressions generated in the `advance_match_arms`. That means that
merging submachines with different output types works, but will then generate
code which will fail to compile.
When converted to Rust code, the state machine will manifest as (among other
things) an enum type which contains all states and which has an `advance`
method. That method consumes the enum value and returns either a new enum
value, an error, or the output type of the state machine.
*/
#[derive(Default)]
pub(crate) struct FromEventsStateMachine {
/// Extra items which are needed for the state machine implementation.
defs: TokenStream,
/// A sequence of enum variant declarations, separated and terminated by
/// commas.
state_defs: TokenStream,
/// A sequence of `match self { .. }` arms, where `self` is the state
/// enumeration type.
///
/// Each match arm must either diverge or return
/// `Result<ControlFlow<State, Output>, xso::error::Error>`, where `State`
/// is the state enumeration and `Output` is the state machine's output
/// type.
advance_match_arms: TokenStream,
/// The different entrypoints for the state machine.
///
/// This may only contain more than one element if an enumeration is being
/// constructed by the resulting state machine.
variants: Vec<FromEventsEntryPoint>,
}
impl From<FromEventsSubmachine> for FromEventsStateMachine {
fn from(other: FromEventsSubmachine) -> Self {
FromEventsStateMachine {
defs: other.defs,
state_defs: other.state_defs,
advance_match_arms: other.advance_match_arms,
variants: vec![FromEventsEntryPoint { init: other.init }],
}
}
}
impl FromEventsStateMachine {
/// Merge another partial state machine into this state machine.
///
/// The state enumeration names from the submachine and this state machine
/// must be disjunct and the machines must have compatible match arms.
pub(crate) fn merge(&mut self, submachine: FromEventsSubmachine) {
self.defs.extend(submachine.defs);
self.state_defs.extend(submachine.state_defs);
self.advance_match_arms
.extend(submachine.advance_match_arms);
self.variants.push(FromEventsEntryPoint {
init: submachine.init,
});
}
/// Partially render the state machine, omitting the `new` function.
///
/// The token stream generated by this function is the same as the token
/// stream generated by [`render()`][`Self::render`], except for the
/// `#builder_ty_name::new` function.
///
/// That function must be created by the caller, or it must construct the
/// builder type in a different way.
///
/// Please see [`render()`][`Self::render`] for details on the arguments.
pub(crate) fn render_partial(
self,
vis: &Visibility,
builder_ty_name: &Ident,
state_ty_ident: &Ident,
output_ty: &Type,
validate: Option<Stmt>,
) -> Result<(TokenStream, Vec<FromEventsEntryPoint>)> {
let Self {
defs,
state_defs,
advance_match_arms,
variants,
} = self;
let output_ty_ref = make_ty_ref(output_ty);
let docstr = format!("Build a {0} from XML events.\n\nThis type is generated using the [`macro@xso::FromXml`] derive macro and implements [`xso::FromEventsBuilder`] for {0}.", output_ty_ref);
Ok((
quote! {
#defs
enum #state_ty_ident {
#state_defs
}
impl #state_ty_ident {
fn advance(mut self, ev: ::xso::exports::rxml::Event) -> ::std::result::Result<::std::ops::ControlFlow<Self, #output_ty>, ::xso::error::Error> {
match self {
#advance_match_arms
}.and_then(|__ok| {
match __ok {
::std::ops::ControlFlow::Break(st) => ::std::result::Result::Ok(::std::ops::ControlFlow::Break(st)),
::std::ops::ControlFlow::Continue(mut result) => {
#validate
::std::result::Result::Ok(::std::ops::ControlFlow::Continue(result))
}
}
})
}
}
impl #builder_ty_name {
fn new(
name: ::xso::exports::rxml::QName,
attrs: ::xso::exports::rxml::AttrMap,
) -> ::std::result::Result<Self, ::xso::FromEventsError> {
#state_ty_ident::new(name, attrs).map(|ok| Self(::std::option::Option::Some(ok)))
}
}
#[doc = #docstr]
#vis struct #builder_ty_name (Option<#state_ty_ident>);
impl ::xso::FromEventsBuilder for #builder_ty_name {
type Output = #output_ty;
fn feed(&mut self, ev: ::xso::exports::rxml::Event) -> ::std::result::Result<::std::option::Option<Self::Output>, ::xso::error::Error> {
let inner = self.0.take().expect("feed called after completion");
match inner.advance(ev)? {
::std::ops::ControlFlow::Continue(value) => ::std::result::Result::Ok(::std::option::Option::Some(value)),
::std::ops::ControlFlow::Break(st) => {
self.0 = Some(st);
::std::result::Result::Ok(::std::option::Option::None)
}
}
}
}
},
variants,
))
}
/// Render the state machine into a type implementing
/// `xso::FromEventsBuilder` by attempting to parse the variants one after
/// another.
///
/// The initializer code in each variant must be an expression which
/// consumes `name: rxml::QName` and `attrs: rxml::AttrMap` (from the
/// start event) and evaluates to a `Result<Self, xso::FromEventsError>`,
/// where `Self` is the state enumeration type.
///
/// The name to use for the type implementing `xso::FromEventsBuilder` must
/// be given as `builder_ty_name`. The state enumeration type will use
/// the name in `state_ty_ident`.
///
/// `output_ty` will be the `xso::FromEventsBuilder::Output` type of the
/// implementation.
///
/// If `validate` is given, it will be inserted such that it is run as the
/// last code before the output value is finally returned. The output value
/// will be available mutably as `result` in that context.
///
/// `vis` must be the desired visibility of the implementation. Note that
/// `vis` must be at least as visible as the visibility of the declaration
/// of `output_ty`.
pub(crate) fn render(
self,
vis: &Visibility,
builder_ty_name: &Ident,
state_ty_ident: &Ident,
output_ty: &Type,
validate: Option<Stmt>,
) -> Result<TokenStream> {
let (defs, variants) =
self.render_partial(vis, builder_ty_name, state_ty_ident, output_ty, validate)?;
let mut init_body = TokenStream::default();
for variant in variants {
let FromEventsEntryPoint { init, .. } = variant;
init_body.extend(quote! {
let (name, mut attrs) = match { { let _ = &mut attrs; } #init } {
::std::result::Result::Ok(v) => return ::std::result::Result::Ok(v),
::std::result::Result::Err(::xso::FromEventsError::Invalid(e)) => return ::std::result::Result::Err(::xso::FromEventsError::Invalid(e)),
::std::result::Result::Err(::xso::FromEventsError::Mismatch { name, attrs }) => (name, attrs),
};
})
}
Ok(quote! {
#defs
impl #state_ty_ident {
fn new(
name: ::xso::exports::rxml::QName,
mut attrs: ::xso::exports::rxml::AttrMap,
) -> ::std::result::Result<Self, ::xso::FromEventsError> {
#init_body
{ let _ = &mut attrs; }
::std::result::Result::Err(::xso::FromEventsError::Mismatch { name, attrs })
}
}
})
}
/// Render the state machine into a type implementing
/// `xso::FromEventsBuilder` by using a `match { .. }` block to
/// distinguish the variants.
///
/// The initializer code in each variant must be a match arm which matches
/// against the value produced by the `match_value` statements. In
/// addition, `fallback` is inserted behind the last initializer code
/// snippet.
///
/// `match_value` must create a local variable called `value`. `value`
/// will be used as expression in the match block for the initializers.
///
/// The name to use for the type implementing `xso::FromEventsBuilder` must
/// be given as `builder_ty_name`. The state enumeration type will use
/// the name in `state_ty_ident`.
///
/// `output_ty` will be the `xso::FromEventsBuilder::Output` type of the
/// implementation.
///
/// If `validate` is given, it will be inserted such that it is run as the
/// last code before the output value is finally returned. The output value
/// will be available mutably as `result` in that context.
///
/// `vis` must be the desired visibility of the implementation. Note that
/// `vis` must be at least as visible as the visibility of the declaration
/// of `output_ty`.
pub(crate) fn render_match(
self,
vis: &Visibility,
builder_ty_name: &Ident,
state_ty_ident: &Ident,
output_ty: &Type,
match_value: TokenStream,
fallback: TokenStream,
validate: Option<Stmt>,
) -> Result<TokenStream> {
let (defs, variants) =
self.render_partial(vis, builder_ty_name, state_ty_ident, output_ty, validate)?;
let mut from_events_body_inner = TokenStream::default();
for variant in variants {
from_events_body_inner.extend(variant.init);
}
Ok(quote! {
#defs
impl #state_ty_ident {
fn new(
name: ::xso::exports::rxml::QName,
mut attrs: ::xso::exports::rxml::AttrMap,
) -> ::std::result::Result<Self, ::xso::FromEventsError> {
#match_value
match value {
#from_events_body_inner
#fallback
}
}
}
})
}
}
pub(crate) struct IntoEventsSubmachine {
pub(crate) defs: TokenStream,
pub(crate) state_defs: TokenStream,
pub(crate) advance_match_arms: TokenStream,
pub(crate) destructure: TokenStream,
pub(crate) init: TokenStream,
}
impl IntoEventsSubmachine {
pub(crate) fn transparent(
inner_ty: &Type,
state_ident: &Ident,
destructure: TokenStream,
init: TokenStream,
) -> Self {
Self {
defs: TokenStream::default(),
state_defs: quote! {
#state_ident(#inner_ty),
},
advance_match_arms: quote! {
Self::#state_ident(mut inner) => {
let ev = inner.next().transpose()?;
let next_state = if ev.is_some() {
::std::option::Option::Some(Self::#state_ident(inner))
} else {
::std::option::Option::None
};
::std::result::Result::Ok((next_state, ev))
},
},
destructure,
init,
}
}
pub(crate) fn augment_init<F: FnOnce(&TokenStream) -> TokenStream>(&mut self, f: F) {
let new_init = f(&self.init);
self.init = new_init;
}
pub(crate) fn augmented_init<F: FnOnce(&TokenStream) -> TokenStream>(mut self, f: F) -> Self {
self.augment_init(f);
self
}
pub(crate) fn render_partial(
self,
vis: &Visibility,
input_ty: &Type,
state_ty_ident: &Ident,
iterator_ty_name: &Ident,
) -> Result<(TokenStream, TokenStream, TokenStream)> {
let statemachine: IntoEventsStateMachine = self.into();
let (defs, mut entrypoints) =
statemachine.render_partial(vis, input_ty, state_ty_ident, iterator_ty_name)?;
assert_eq!(entrypoints.len(), 1);
let IntoEventsEntryPoint { destructure, init } = entrypoints.remove(0);
Ok((defs, destructure, init))
}
pub(crate) fn render(
self,
vis: &Visibility,
input_ty: &Type,
state_ty_ident: &Ident,
iterator_ty_name: &Ident,
) -> Result<TokenStream> {
let statemachine: IntoEventsStateMachine = self.into();
statemachine.render(vis, input_ty, state_ty_ident, iterator_ty_name)
}
}
pub(crate) struct IntoEventsEntryPoint {
destructure: TokenStream,
init: TokenStream,
}
#[derive(Default)]
pub(crate) struct IntoEventsStateMachine {
defs: TokenStream,
state_defs: TokenStream,
advance_match_arms: TokenStream,
variants: Vec<IntoEventsEntryPoint>,
}
impl From<IntoEventsSubmachine> for IntoEventsStateMachine {
fn from(other: IntoEventsSubmachine) -> Self {
Self::new(
other.defs,
other.state_defs,
other.advance_match_arms,
other.destructure,
other.init,
)
}
}
impl IntoEventsStateMachine {
fn new(
defs: TokenStream,
state_defs: TokenStream,
advance_match_arms: TokenStream,
destructure: TokenStream,
init: TokenStream,
) -> Self {
Self {
defs,
state_defs,
advance_match_arms,
variants: vec![IntoEventsEntryPoint { destructure, init }],
}
}
pub(crate) fn merge(&mut self, submachine: IntoEventsSubmachine) {
self.push(
IntoEventsEntryPoint {
destructure: submachine.destructure,
init: submachine.init,
},
submachine.defs,
submachine.state_defs,
submachine.advance_match_arms,
)
}
fn push(
&mut self,
entrypoint: IntoEventsEntryPoint,
defs: TokenStream,
state_defs: TokenStream,
advance_match_arms: TokenStream,
) {
self.defs.extend(defs);
self.state_defs.extend(state_defs);
self.advance_match_arms.extend(advance_match_arms);
self.variants.push(entrypoint);
}
fn render_partial(
self,
vis: &Visibility,
input_ty: &Type,
state_ty_ident: &Ident,
iterator_ty_name: &Ident,
) -> Result<(TokenStream, Vec<IntoEventsEntryPoint>)> {
let Self {
defs,
state_defs,
advance_match_arms,
variants,
} = self;
let input_ty_ref = make_ty_ref(input_ty);
let docstr = format!("Convert a {0} into XML events.\n\nThis type is generated using the [`macro@xso::IntoXml`] derive macro and implements [`std::iter:Iterator`] for {0}.", input_ty_ref);
Ok((
quote! {
#defs
enum #state_ty_ident {
#state_defs
}
impl #state_ty_ident {
fn advance(mut self) -> ::std::result::Result<(::std::option::Option<Self>, ::std::option::Option<::xso::exports::rxml::Event>), ::xso::error::Error> {
match self {
#advance_match_arms
}
}
}
#[doc = #docstr]
#vis struct #iterator_ty_name (Option<#state_ty_ident>);
impl ::std::iter::Iterator for #iterator_ty_name {
type Item = Result<::xso::exports::rxml::Event, ::xso::error::Error>;
fn next(&mut self) -> ::std::option::Option<Self::Item> {
let mut state = self.0.take()?;
loop {
let (next_state, ev) = match state.advance() {
::std::result::Result::Ok(v) => v,
::std::result::Result::Err(e) => return ::std::option::Option::Some(Err(e)),
};
if let ::std::option::Option::Some(ev) = ev {
self.0 = next_state;
return ::std::option::Option::Some(::std::result::Result::Ok(ev));
}
// no event, do we have a state?
if let ::std::option::Option::Some(st) = next_state {
// we do: try again!
state = st;
continue;
} else {
// we don't: end of iterator!
self.0 = ::std::option::Option::None;
return ::std::option::Option::None;
}
}
}
}
},
variants,
))
}
pub(crate) fn render(
self,
vis: &Visibility,
input_ty: &Type,
state_ty_ident: &Ident,
iterator_ty_name: &Ident,
) -> Result<TokenStream> {
let (defs, mut variants) =
self.render_partial(vis, input_ty, state_ty_ident, iterator_ty_name)?;
let init_body = if variants.len() == 1 {
let IntoEventsEntryPoint { destructure, init } = variants.remove(0);
quote! {
{
let #destructure = value;
#init
}
}
} else {
let mut match_arms = TokenStream::default();
for IntoEventsEntryPoint { destructure, init } in variants {
match_arms.extend(quote! {
#destructure => #init,
});
}
quote! {
match value {
#match_arms
}
}
};
Ok(quote! {
#defs
impl #state_ty_ident {
fn new(
value: #input_ty,
) -> ::std::result::Result<Self, ::xso::error::Error> {
::std::result::Result::Ok(#init_body)
}
}
impl #iterator_ty_name {
fn new(value: #input_ty) -> ::std::result::Result<Self, ::xso::error::Error> {
#state_ty_ident::new(value).map(|ok| Self(::std::option::Option::Some(ok)))
}
}
})
}
}
#[derive(Clone, Copy)]
pub(crate) enum ScopeNamespace<'x> {
Static(&'x Path),
Dyn(&'x Member),
Unavailable,
}
pub(crate) struct Scope {
pub(crate) state_prefix: String,
pub(crate) type_prefix: Ident,
pub(crate) default_state_ident: Ident,
pub(crate) attrs: Ident,
pub(crate) start_ev_qname: Ident,
pub(crate) start_ev_attrs: Ident,
pub(crate) text: Ident,
pub(crate) substate_result: Ident,
pub(crate) builder_data: Ident,
pub(crate) namespace_local: Expr,
pub(crate) namespace_access: Expr,
}
impl Scope {
pub(crate) fn new(
namespace: ScopeNamespace,
state_prefix: &str,
type_prefix: Ident,
span: &Span,
) -> Self {
let builder_data = Ident::new("__data", *span);
let (namespace_local, namespace_access) = match namespace {
ScopeNamespace::Static(ns) => {
let expr = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: ns.clone(),
});
(expr.clone(), expr)
}
ScopeNamespace::Dyn(ns) => {
let ns_span = ns.span();
let access = Self::access_field_static(&builder_data, ns);
let local = Self::mangle_field_static(ns);
let local = Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: local.into(),
});
(
local.clone(),
Expr::Reference(ExprReference {
attrs: Vec::new(),
and_token: syn::token::And { spans: [ns_span] },
mutability: None,
expr: Box::new(access),
}),
)
}
ScopeNamespace::Unavailable => {
let expr = Expr::Macro(ExprMacro {
attrs: Vec::new(),
mac: Macro {
path: Ident::new("compile_error", Span::call_site()).into(),
bang_token: syn::token::Not {
spans: [Span::call_site()],
},
delimiter: MacroDelimiter::Paren(syn::token::Paren::default()),
tokens: quote! { "internal xso-proc error: attempt to use container namespace in a context where it is not available." },
},
});
(expr.clone(), expr)
}
};
static SUBSTATE_STR: &'static str = "Substate";
let mut state_prefix_buf = String::with_capacity(state_prefix.len() + SUBSTATE_STR.len());
state_prefix_buf.push_str(state_prefix);
state_prefix_buf.push_str(SUBSTATE_STR);
Self {
state_prefix: state_prefix_buf,
default_state_ident: quote::format_ident!("{}Default", state_prefix),
attrs: Ident::new("attrs", *span),
start_ev_qname: Ident::new("__ev_qname", *span),
start_ev_attrs: Ident::new("__ev_attrs", *span),
text: Ident::new("__text_content", *span),
substate_result: Ident::new("__parsed_substate", *span),
builder_data,
namespace_local,
namespace_access,
type_prefix,
}
}
fn access_field_static(builder_data: &Ident, member: &Member) -> Expr {
let mangled = Self::mangle_field_static(member);
Expr::Field(ExprField {
attrs: Vec::new(),
base: Box::new(Expr::Path(ExprPath {
attrs: Vec::new(),
qself: None,
path: builder_data.clone().into(),
})),
dot_token: syn::token::Dot {
spans: [Span::call_site()],
},
member: Member::Named(mangled),
})
}
pub(crate) fn access_field(&self, member: &Member) -> Expr {
Self::access_field_static(&self.builder_data, member)
}
pub(crate) fn mangle_field_static(member: &Member) -> Ident {
mangle_into_snake_case_name(member, "f_")
}
pub(crate) fn mangle_field(&self, member: &Member) -> Ident {
Self::mangle_field_static(member)
}
pub(crate) fn mangle_state(&self, member: &Member) -> Ident {
mangle_into_camel_case_name(member, &self.state_prefix)
}
}
pub(crate) enum SomeName<'x> {
Index((u32, Span)),
Ident(Ident),
IdentRef(&'x Ident),
}
impl From<Member> for SomeName<'static> {
fn from(other: Member) -> Self {
match other {
Member::Named(named) => Self::Ident(named),
Member::Unnamed(index) => Self::Index((index.index, index.span)),
}
}
}
impl<'x> From<&'x Member> for SomeName<'x> {
fn from(other: &'x Member) -> Self {
match other {
Member::Named(ref named) => Self::IdentRef(named),
Member::Unnamed(index) => Self::Index((index.index, index.span)),
}
}
}
impl From<Ident> for SomeName<'static> {
fn from(other: Ident) -> Self {
Self::Ident(other)
}
}
impl<'x> From<&'x Ident> for SomeName<'x> {
fn from(other: &'x Ident) -> Self {
Self::IdentRef(other)
}
}
impl<'x> SomeName<'x> {
fn into_member(self) -> Member {
match self {
Self::Index((index, span)) => Member::Unnamed(Index { index, span }),
Self::Ident(ident) => Member::Named(ident),
Self::IdentRef(ident) => Member::Named(ident.clone()),
}
}
}
pub(crate) fn mangle_into_camel_case_name<'x, T: Into<SomeName<'x>>>(s: T, prefix: &str) -> Ident {
let s = s.into();
let s = s.into_member();
let (ident, span) = match s {
Member::Unnamed(index) => (format!("{}U{}", prefix, index.index), index.span),
Member::Named(ident) => {
let span = ident.span();
let ident = ident.to_string();
let mut buffer: String = String::with_capacity(ident.len() + prefix.len());
buffer.push_str(prefix);
for segment in ident.split_inclusive(['_', 'U']) {
let len = segment.len();
assert!(len > 0); // split_inclusive should never be empty for a non-empty string
let last = segment.as_bytes()[len - 1];
let (escape_sequence, segment) = match last {
b'_' => ("Underscore", &segment[..len - 1]),
b'U' => ("UU", &segment[..len - 1]),
_ => ("", segment),
};
buffer.push_str(segment);
buffer.push_str(escape_sequence);
}
let Some(first) = buffer.chars().next() else {
unreachable!()
};
if first.is_lowercase() {
let upper_buf = String::from_iter(first.to_uppercase());
buffer.replace_range(..first.len_utf8(), &upper_buf);
}
(buffer, span)
}
};
Ident::new(&ident, span)
}
pub(crate) fn mangle_into_snake_case_name<'x, T: Into<SomeName<'x>>>(s: T, prefix: &str) -> Ident {
let s = s.into();
let s = s.into_member();
let (ident, span) = match s {
Member::Unnamed(index) => (format!("{}u_{}", prefix, index.index), index.span),
Member::Named(ident) => {
let span = ident.span();
let ident = ident.to_string();
let mut buffer: String = String::with_capacity(ident.len() + prefix.len());
buffer.push_str(prefix);
for ch in ident.chars() {
if ch == '_' {
buffer.push_str("_underscore_");
} else if ch.is_ascii_uppercase() {
buffer.push_str("_");
for new_ch in ch.to_lowercase() {
buffer.push(new_ch);
}
} else {
buffer.push(ch);
}
}
(buffer, span)
}
};
Ident::new(&ident, span)
}
fn suffixed_ty_name(ty_name: &Ident, suffix: &str) -> Ident {
// The main issue here is the `non_camel_case_types` lint: There is one
// class of identifiers which do not trigger `non_camel_case_types' on
// their own, but will trigger it if another fine identifier is appended:
// those ending in a `_`.
let span = ty_name.span();
let name = ty_name.to_string();
// here, we assume that a user won't have both `Foo` and `Foo_` in scope.
// if they do … well, that's on them and they can always override the
// generated type name.
let name = format!("{}{}", name.trim_matches('_'), suffix);
Ident::new(&name, span)
}
/// Take an identifier and append the suffix `FromEvents` in a way that it
/// won't trigger any rustc lints.
pub(crate) fn make_builder_name(ty_name: &Ident) -> Ident {
suffixed_ty_name(ty_name, "FromEvents")
}
/// Take an identifier and append the suffix `IntoEvents` in a way that it
/// won't trigger any rustc lints.
pub(crate) fn make_iterator_name(ty_name: &Ident) -> Ident {
suffixed_ty_name(ty_name, "IntoEvents")
}
fn doc_link_path(ty: &Type) -> Option<String> {
match ty {
Type::Path(ref ty) => {
let (mut buf, offset) = match ty.qself {
Some(ref qself) => {
let mut buf = doc_link_path(&qself.ty)?;
buf.push_str("::");
(buf, qself.position)
}
None => {
let mut buf = String::new();
if ty.path.leading_colon.is_some() {
buf.push_str("::");
}
(buf, 0)
}
};
let last = ty.path.segments.len() - 1;
for i in offset..ty.path.segments.len() {
let segment = &ty.path.segments[i];
buf.push_str(&segment.ident.to_string());
if i < last {
buf.push_str("::");
}
}
Some(buf)
}
_ => None,
}
}
/// Create a markdown snippet which references the given type as cleanly as
/// possible.
///
/// This is used in documentation generation functions.
///
/// Not all types can be linked to; those which cannot be linked to will
/// simply be wrapped in backticks.
pub(crate) fn make_ty_ref(ty: &Type) -> String {
match doc_link_path(ty) {
Some(mut path) => {
path.reserve(4);
path.insert_str(0, "[`");
path.push_str("`]");
path
}
None => format!("`{}`", ty.to_token_stream()),
}
}