lib.rs

  1// Copyright (c) 2024 Jonas Schäfer <jonas@zombofant.net>
  2//
  3// This Source Code Form is subject to the terms of the Mozilla Public
  4// License, v. 2.0. If a copy of the MPL was not distributed with this
  5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6
  7#![forbid(unsafe_code)]
  8#![warn(missing_docs)]
  9#![allow(rustdoc::private_intra_doc_links)]
 10/*!
 11# Macros for parsing XML into Rust structs, and vice versa
 12
 13**If you are a user of `xso_proc` or `xso`, please
 14return to `xso` for more information**. The documentation of
 15`xso_proc` is geared toward developers of `…_macros` and `…_core`.
 16
 17**You have been warned.**
 18*/
 19
 20// Wondering about RawTokenStream vs. TokenStream?
 21// syn mostly works with proc_macro2, while the proc macros themselves use
 22// proc_macro.
 23use proc_macro::TokenStream as RawTokenStream;
 24use proc_macro2::TokenStream;
 25use quote::quote;
 26use syn::*;
 27
 28mod meta;
 29
 30/// Convert an [`syn::Item`] into the parts relevant for us.
 31///
 32/// If the item is of an unsupported variant, an appropriate error is
 33/// returned.
 34fn parse_struct(item: Item) -> Result<(Visibility, meta::XmlCompoundMeta, Ident)> {
 35    match item {
 36        Item::Struct(item) => {
 37            match item.fields {
 38                Fields::Unit => (),
 39                other => {
 40                    return Err(Error::new_spanned(
 41                        other,
 42                        "cannot derive on non-unit struct (yet!)",
 43                    ))
 44                }
 45            }
 46            let meta = meta::XmlCompoundMeta::parse_from_attributes(&item.attrs)?;
 47            Ok((item.vis, meta, item.ident))
 48        }
 49        other => Err(Error::new_spanned(other, "cannot derive on this item")),
 50    }
 51}
 52
 53/// Generate a `xso::FromXml` implementation for the given item, or fail with
 54/// a proper compiler error.
 55fn from_xml_impl(input: Item) -> Result<TokenStream> {
 56    let (
 57        vis,
 58        meta::XmlCompoundMeta {
 59            namespace,
 60            name,
 61            span,
 62        },
 63        ident,
 64    ) = parse_struct(input)?;
 65
 66    // we rebind to a different name here because otherwise some expressions
 67    // inside `quote! {}` below get a bit tricky to read (such as
 68    // `name.1 == #name`).
 69    let Some(xml_namespace) = namespace else {
 70        return Err(Error::new(span, "`namespace` key is required"));
 71    };
 72
 73    let Some(xml_name) = name else {
 74        return Err(Error::new(span, "`name` key is required"));
 75    };
 76
 77    let from_events_builder_ty_name = quote::format_ident!("{}FromEvents", ident);
 78    let state_ty_name = quote::format_ident!("{}FromEventsState", ident);
 79
 80    let unknown_attr_err = format!(
 81        "Unknown attribute in {} element.",
 82        xml_name.repr_to_string()
 83    );
 84    let unknown_child_err = format!("Unknown child in {} element.", xml_name.repr_to_string());
 85    let docstr = format!("Build a [`{}`] from XML events", ident);
 86
 87    #[cfg_attr(not(feature = "minidom"), allow(unused_mut))]
 88    let mut result = quote! {
 89        enum #state_ty_name {
 90            Default,
 91        }
 92
 93        #[doc = #docstr]
 94        #vis struct #from_events_builder_ty_name(::core::option::Option<#state_ty_name>);
 95
 96        impl ::xso::FromEventsBuilder for #from_events_builder_ty_name {
 97            type Output = #ident;
 98
 99            fn feed(
100                &mut self,
101                ev: ::xso::exports::rxml::Event
102            ) -> ::core::result::Result<::core::option::Option<Self::Output>, ::xso::error::Error> {
103                match self.0 {
104                    ::core::option::Option::None => panic!("feed() called after it returned a non-None value"),
105                    ::core::option::Option::Some(#state_ty_name::Default) => match ev {
106                        ::xso::exports::rxml::Event::StartElement(..) => {
107                            ::core::result::Result::Err(::xso::error::Error::Other(#unknown_child_err))
108                        }
109                        ::xso::exports::rxml::Event::EndElement(..) => {
110                            self.0 = ::core::option::Option::None;
111                            ::core::result::Result::Ok(::core::option::Option::Some(#ident))
112                        }
113                        ::xso::exports::rxml::Event::Text(..) => {
114                            ::core::result::Result::Err(::xso::error::Error::Other("Unexpected text content".into()))
115                        }
116                        // we ignore these: a correct parser only generates
117                        // them at document start, and there we want to indeed
118                        // not worry about them being in front of the first
119                        // element.
120                        ::xso::exports::rxml::Event::XmlDeclaration(_, ::xso::exports::rxml::XmlVersion::V1_0) => ::core::result::Result::Ok(::core::option::Option::None)
121                    }
122                }
123            }
124        }
125
126        impl ::xso::FromXml for #ident {
127            type Builder = #from_events_builder_ty_name;
128
129            fn from_events(
130                name: ::xso::exports::rxml::QName,
131                attrs: ::xso::exports::rxml::AttrMap,
132            ) -> ::core::result::Result<Self::Builder, ::xso::error::FromEventsError> {
133                if name.0 != #xml_namespace || name.1 != #xml_name {
134                    return ::core::result::Result::Err(::xso::error::FromEventsError::Mismatch { name, attrs });
135                }
136                if attrs.len() > 0 {
137                    return ::core::result::Result::Err(::xso::error::Error::Other(#unknown_attr_err).into());
138                }
139                ::core::result::Result::Ok(#from_events_builder_ty_name(::core::option::Option::Some(#state_ty_name::Default)))
140            }
141        }
142    };
143
144    #[cfg(feature = "minidom")]
145    result.extend(quote! {
146        impl ::std::convert::TryFrom<::xso::exports::minidom::Element> for #ident {
147            type Error = ::xso::error::FromElementError;
148
149            fn try_from(other: ::xso::exports::minidom::Element) -> ::core::result::Result<Self, Self::Error> {
150                ::xso::try_from_element(other)
151            }
152        }
153    });
154
155    Ok(result)
156}
157
158/// Macro to derive a `xso::FromXml` implementation on a type.
159///
160/// The user-facing documentation for this macro lives in the `xso` crate.
161#[proc_macro_derive(FromXml, attributes(xml))]
162pub fn from_xml(input: RawTokenStream) -> RawTokenStream {
163    // Shim wrapper around `from_xml_impl` which converts any errors into
164    // actual compiler errors within the resulting token stream.
165    let item = syn::parse_macro_input!(input as Item);
166    match from_xml_impl(item) {
167        Ok(v) => v.into(),
168        Err(e) => e.into_compile_error().into(),
169    }
170}
171
172/// Generate a `xso::IntoXml` implementation for the given item, or fail with
173/// a proper compiler error.
174fn into_xml_impl(input: Item) -> Result<TokenStream> {
175    let (
176        vis,
177        meta::XmlCompoundMeta {
178            namespace,
179            name,
180            span,
181        },
182        ident,
183    ) = parse_struct(input)?;
184
185    // we rebind to a different name here to stay consistent with
186    // `from_xml_impl`.
187    let Some(xml_namespace) = namespace else {
188        return Err(Error::new(span, "`namespace` key is required"));
189    };
190
191    let Some(xml_name) = name else {
192        return Err(Error::new(span, "`name` key is required"));
193    };
194
195    let into_events_iter_ty_name = quote::format_ident!("{}IntoEvents", ident);
196    let state_ty_name = quote::format_ident!("{}IntoEventsState", ident);
197
198    let docstr = format!("Decompose a [`{}`] into XML events", ident);
199
200    #[cfg_attr(not(feature = "minidom"), allow(unused_mut))]
201    let mut result = quote! {
202        enum #state_ty_name {
203            Header,
204            Footer,
205        }
206
207        #[doc = #docstr]
208        #vis struct #into_events_iter_ty_name(::core::option::Option<#state_ty_name>);
209
210        impl ::std::iter::Iterator for #into_events_iter_ty_name {
211            type Item = ::core::result::Result<::xso::exports::rxml::Event, ::xso::error::Error>;
212
213            fn next(&mut self) -> ::core::option::Option<Self::Item> {
214                match self.0 {
215                    ::core::option::Option::Some(#state_ty_name::Header) => {
216                        self.0 = ::core::option::Option::Some(#state_ty_name::Footer);
217                        ::core::option::Option::Some(::core::result::Result::Ok(::xso::exports::rxml::Event::StartElement(
218                            ::xso::exports::rxml::parser::EventMetrics::zero(),
219                            (
220                                ::xso::exports::rxml::Namespace::from_str(#xml_namespace),
221                                #xml_name.to_owned(),
222                            ),
223                            ::xso::exports::rxml::AttrMap::new(),
224                        )))
225                    }
226                    ::core::option::Option::Some(#state_ty_name::Footer) => {
227                        self.0 = ::core::option::Option::None;
228                        ::core::option::Option::Some(::core::result::Result::Ok(::xso::exports::rxml::Event::EndElement(
229                            ::xso::exports::rxml::parser::EventMetrics::zero(),
230                        )))
231                    }
232                    ::core::option::Option::None => ::core::option::Option::None,
233                }
234            }
235        }
236
237        impl ::xso::IntoXml for #ident {
238            type EventIter = #into_events_iter_ty_name;
239
240            fn into_event_iter(self) -> ::core::result::Result<Self::EventIter, ::xso::error::Error> {
241                ::core::result::Result::Ok(#into_events_iter_ty_name(::core::option::Option::Some(#state_ty_name::Header)))
242            }
243        }
244    };
245
246    #[cfg(all(feature = "minidom", feature = "panicking-into-impl"))]
247    result.extend(quote! {
248        impl ::std::convert::From<#ident> for ::xso::exports::minidom::Element {
249            fn from(other: #ident) -> Self {
250                ::xso::transform(other).expect("seamless conversion into minidom::Element")
251            }
252        }
253    });
254
255    #[cfg(all(feature = "minidom", not(feature = "panicking-into-impl")))]
256    result.extend(quote! {
257        impl ::std::convert::TryFrom<#ident> for ::xso::exports::minidom::Element {
258            type Error = ::xso::error::Error;
259
260            fn try_from(other: #ident) -> ::core::result::Result<Self, Self::Error> {
261                ::xso::transform(other)
262            }
263        }
264    });
265
266    Ok(result)
267}
268
269/// Macro to derive a `xso::IntoXml` implementation on a type.
270///
271/// The user-facing documentation for this macro lives in the `xso` crate.
272#[proc_macro_derive(IntoXml, attributes(xml))]
273pub fn into_xml(input: RawTokenStream) -> RawTokenStream {
274    // Shim wrapper around `into_xml_impl` which converts any errors into
275    // actual compiler errors within the resulting token stream.
276    let item = syn::parse_macro_input!(input as Item);
277    match into_xml_impl(item) {
278        Ok(v) => v.into(),
279        Err(e) => e.into_compile_error().into(),
280    }
281}