Skip to content

Implement `#[derive(FromXml, IntoXml)]`

Jonas Schäfer requested to merge jssfr/xmpp-rs:feature/derive-macro-part-1 into main

This entire MR deserves some explanation.

  1. Why move from the macro_rules! approach to a derive macro?

A derive macro is much more idiomatic to Rust. The macro_rules!-based approach, while pretty clever and full-featured, is very opaque and unclear to crate (but not partiuclarly Rust) newcomers. Not to mention that the implementation, with all the variations it handles in the rather functional macro_rules!-language, got very unwieldly and hard to maintain.

  1. Why add a xso crate? What is its purpose and its relation to xmpp_parsers and xso_proc?

From the code generated within the derive macro, we have to refer to some traits and/or types we define. We cannot define these in the xso_proc crate, because proc macro crates can only export proc macros, no other items.

We also need to refer to these types unambiguously. As we don't know which names are imported in the scopes the derive macro is invoked in, we have to use absolute paths (such as ::foo::bar).

That means we need a crate name.

Now there are two non-options:

  • We could use crate::. That has the downside that the derive macro is only useful within the xmpp_parsers crate. It cannot be used outside, unless the traits are re-imported there.

  • We could use ::xmpp_parsers::.., except, we can't: That would prevent use of the macro within xmpp_parsers, because crates cannot refer to themselves by name.

So the only way that makes sense is to have a xso crate which contains the traits as well as some basic implementations needed for the macros to work, re-export the derive macros from there, and depend on that crate from xmpp_parsers.

  1. Oh god this is complex, how do I learn more or hack on this??

Run cargo doc --document-private-items. The xso_proc crate is fully documented in the private areas, and that makes that documentation quite accessible in your browser.

Edited by Jonas Schäfer

Merge request reports