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::{Span, TokenStream};
25use quote::quote;
26use syn::*;
27
28mod compound;
29mod error_message;
30mod field;
31mod meta;
32mod scope;
33mod state;
34mod structs;
35mod types;
36
37/// Convert an [`syn::Item`] into the parts relevant for us.
38///
39/// If the item is of an unsupported variant, an appropriate error is
40/// returned.
41fn parse_struct(item: Item) -> Result<(Visibility, Ident, structs::StructDef)> {
42 match item {
43 Item::Struct(item) => {
44 let meta = meta::XmlCompoundMeta::parse_from_attributes(&item.attrs)?;
45 let def = structs::StructDef::new(&item.ident, meta, &item.fields)?;
46 Ok((item.vis, item.ident, def))
47 }
48 other => Err(Error::new_spanned(other, "cannot derive on this item")),
49 }
50}
51
52/// Generate a `xso::FromXml` implementation for the given item, or fail with
53/// a proper compiler error.
54fn from_xml_impl(input: Item) -> Result<TokenStream> {
55 let (vis, ident, def) = parse_struct(input)?;
56
57 let name_ident = Ident::new("name", Span::call_site());
58 let attrs_ident = Ident::new("attrs", Span::call_site());
59
60 let structs::FromXmlParts {
61 defs,
62 from_events_body,
63 builder_ty_ident,
64 } = def.make_from_events_builder(&vis, &name_ident, &attrs_ident)?;
65
66 #[cfg_attr(not(feature = "minidom"), allow(unused_mut))]
67 let mut result = quote! {
68 #defs
69
70 impl ::xso::FromXml for #ident {
71 type Builder = #builder_ty_ident;
72
73 fn from_events(
74 name: ::xso::exports::rxml::QName,
75 attrs: ::xso::exports::rxml::AttrMap,
76 ) -> ::core::result::Result<Self::Builder, ::xso::error::FromEventsError> {
77 #from_events_body
78 }
79 }
80 };
81
82 #[cfg(feature = "minidom")]
83 result.extend(quote! {
84 impl ::std::convert::TryFrom<::xso::exports::minidom::Element> for #ident {
85 type Error = ::xso::error::FromElementError;
86
87 fn try_from(other: ::xso::exports::minidom::Element) -> ::core::result::Result<Self, Self::Error> {
88 ::xso::try_from_element(other)
89 }
90 }
91 });
92
93 if def.debug() {
94 println!("{}", result);
95 }
96
97 Ok(result)
98}
99
100/// Macro to derive a `xso::FromXml` implementation on a type.
101///
102/// The user-facing documentation for this macro lives in the `xso` crate.
103#[proc_macro_derive(FromXml, attributes(xml))]
104pub fn from_xml(input: RawTokenStream) -> RawTokenStream {
105 // Shim wrapper around `from_xml_impl` which converts any errors into
106 // actual compiler errors within the resulting token stream.
107 let item = syn::parse_macro_input!(input as Item);
108 match from_xml_impl(item) {
109 Ok(v) => v.into(),
110 Err(e) => e.into_compile_error().into(),
111 }
112}
113
114/// Generate a `xso::AsXml` implementation for the given item, or fail with
115/// a proper compiler error.
116fn as_xml_impl(input: Item) -> Result<TokenStream> {
117 let (vis, ident, def) = parse_struct(input)?;
118
119 let structs::AsXmlParts {
120 defs,
121 as_xml_iter_body,
122 item_iter_ty_lifetime,
123 item_iter_ty,
124 } = def.make_as_xml_iter(&vis)?;
125
126 #[cfg_attr(not(feature = "minidom"), allow(unused_mut))]
127 let mut result = quote! {
128 #defs
129
130 impl ::xso::AsXml for #ident {
131 type ItemIter<#item_iter_ty_lifetime> = #item_iter_ty;
132
133 fn as_xml_iter(&self) -> ::core::result::Result<Self::ItemIter<'_>, ::xso::error::Error> {
134 #as_xml_iter_body
135 }
136 }
137 };
138
139 #[cfg(all(feature = "minidom", feature = "panicking-into-impl"))]
140 result.extend(quote! {
141 impl ::std::convert::From<#ident> for ::xso::exports::minidom::Element {
142 fn from(other: #ident) -> Self {
143 ::xso::transform(other).expect("seamless conversion into minidom::Element")
144 }
145 }
146 });
147
148 #[cfg(all(feature = "minidom", not(feature = "panicking-into-impl")))]
149 result.extend(quote! {
150 impl ::std::convert::TryFrom<#ident> for ::xso::exports::minidom::Element {
151 type Error = ::xso::error::Error;
152
153 fn try_from(other: #ident) -> ::core::result::Result<Self, Self::Error> {
154 ::xso::transform(other)
155 }
156 }
157 });
158
159 if def.debug() {
160 println!("{}", result);
161 }
162
163 Ok(result)
164}
165
166/// Macro to derive a `xso::AsXml` implementation on a type.
167///
168/// The user-facing documentation for this macro lives in the `xso` crate.
169#[proc_macro_derive(AsXml, attributes(xml))]
170pub fn as_xml(input: RawTokenStream) -> RawTokenStream {
171 // Shim wrapper around `as_xml_impl` which converts any errors into
172 // actual compiler errors within the resulting token stream.
173 let item = syn::parse_macro_input!(input as Item);
174 match as_xml_impl(item) {
175 Ok(v) => v.into(),
176 Err(e) => e.into_compile_error().into(),
177 }
178}