parsyng_proc_macros/lib.rs
1//! Implementation of the [`proc_macro`](proc_macro_), [`proc_macro_attribute`](proc_macro_attribute_)
2//! and the [`proc_macro_derive`](proc_macro_derive_) procedural macros, and [`Parse`], [`ToTokens`] derive macros for `parsyng`.
3//!
4//! This crate only depends on the compiler's `proc_macro`, not on
5//! `parsyng-core`, so that both compile in parallel: it walks just the
6//! outline of its input (see `tokens`) and passes every other token through.
7
8#![deny(
9 clippy::all,
10 clippy::pedantic,
11 clippy::nursery,
12 clippy::cargo,
13 rustdoc::all,
14 rustdoc::redundant_explicit_links,
15 invalid_doc_attributes,
16 unused_doc_comments,
17 missing_docs
18)]
19
20use proc_macro::{Ident, Literal, Span, TokenStream};
21
22mod derive_parse;
23mod derive_to_tokens;
24mod helper_common;
25mod proc_macro_attribute_helper;
26mod proc_macro_derive_helper;
27mod proc_macro_helper;
28mod tokens;
29
30use tokens::Out;
31
32/// `parsyng::debug_stream("<macro>", "<location>", &output);`
33pub(crate) fn dbg_macros(macro_name: &Ident) -> Out {
34 let location = format!(
35 "{}:{}:{}",
36 Span::call_site().file(),
37 Span::call_site().line(),
38 Span::call_site().column()
39 );
40 let mut args = Out::new();
41 args.tree(Literal::string(¯o_name.to_string()))
42 .src(",")
43 .tree(Literal::string(&location))
44 .src(", &output");
45 let mut out = Out::new();
46 out.src("parsyng::debug_stream")
47 .group(proc_macro::Delimiter::Parenthesis, args)
48 .src(";");
49 out
50}
51
52/// Helper attribute to build new procedural macros. This replaces the
53/// standard library's `#[proc_macro]` attribute.
54///
55/// It differs from the standard library's by allowing any input type that
56/// implements the [`Parse`](https://docs.rs/parsyng/latest/parsyng/parse/trait.Parse.html) trait — the input is parsed
57/// automatically, and a parse failure is turned into a `compile_error!` at
58/// the offending span instead of panicking the proc-macro process. It allows
59/// any output type that implements [`ToTokens`](https://docs.rs/parsyng/latest/parsyng/trait.ToTokens.html),
60/// automatically converting it into a [`TokenStream`]. Since
61/// [`Result<T, E>`](Result) implements [`ToTokens`](https://docs.rs/parsyng/latest/parsyng/trait.ToTokens.html)
62/// whenever `T` and `E` do (and `error::Diagnostics` implements it too), the
63/// annotated function can return `error::Result<T>` to fail with a spanned
64/// diagnostic from inside the macro body too, not just during argument
65/// parsing.
66///
67/// # Example
68/// ```
69/// # const IGNORE_TOKENS: &str = stringify! {
70/// #[parsyng::proc_macro]
71/// # };
72/// pub fn add_one(n: u8) -> u8 {
73/// n + 1
74/// }
75/// ```
76/// and then
77/// ```
78/// # fn add_one(n: u8) -> u8 {
79/// # n + 1
80/// # }
81/// # macro_rules! add_one {
82/// # ($n:expr) => {
83/// # add_one($n)
84/// # };
85/// # }
86/// println!("{}", add_one!(5));
87/// // Output : 6
88/// # assert_eq!(add_one!(5), 6);
89/// ```
90///
91/// # The `debug` argument
92///
93/// `#[parsyng::proc_macro(debug)]` prints the macro's generated output to
94/// stderr at every call site, which is invaluable when the macro emits
95/// syntax invalid enough that `cargo expand` itself can't recover — see
96/// `examples/debug-attribute` for a worked example. Enable the
97/// `debug-pretty` feature on `parsyng` to have that output passed through
98/// `rustfmt` first.
99// Export with an underscore, since it will conflicts with the `proc_macro` builtin.
100#[proc_macro_attribute]
101pub fn proc_macro_(args: TokenStream, input: TokenStream) -> TokenStream {
102 match proc_macro_helper::proc_macro(args, input) {
103 Ok(ok) => ok,
104 Err(err) => err.into_compile_error(),
105 }
106}
107
108/// Helper attribute to build new procedural macro attributes. This replaces
109/// the standard library's `#[proc_macro_attribute]` attribute.
110///
111/// Like [`proc_macro`](proc_macro_), it lets the annotated function take
112/// typed, [`Parse`](https://docs.rs/parsyng/latest/parsyng/parse/trait.Parse.html)-implementing arguments — one for
113/// the attribute's own arguments (`attr` in `#[my_attr(attr)] item`), one
114/// for the annotated item — and return any
115/// [`ToTokens`](https://docs.rs/parsyng/latest/parsyng/trait.ToTokens.html) value, instead of manually parsing
116/// two `proc_macro::TokenStream`s and matching on the results.
117///
118/// Accepts the same optional `debug` argument as
119/// [`proc_macro`](proc_macro_) (see its documentation for details).
120///
121/// # Example
122/// ```
123/// use parsyng::ast::item::Item;
124/// use parsyng::error::Result;
125///
126/// # const IGNORE_TOKENS: &str = stringify! {
127/// #[parsyng::proc_macro_attribute]
128/// # };
129/// pub fn my_attribute(_attr: (), item: Item) -> Result<Item> {
130/// // inspect or rewrite `item` here
131/// Ok(item)
132/// }
133/// # let item = my_attribute((), parsyng::parse_quote!(struct S;)).unwrap();
134/// # assert_eq!(parsyng::ToTokens::to_token_stream(&item).to_string(), "struct S ;");
135/// ```
136// Export with an underscore, since it will conflicts with the `proc_macro_attribute` builtin.
137#[proc_macro_attribute]
138pub fn proc_macro_attribute_(args: TokenStream, input: TokenStream) -> TokenStream {
139 match proc_macro_attribute_helper::proc_macro_attribute(args, input) {
140 Ok(ok) => ok,
141 Err(err) => err.into_compile_error(),
142 }
143}
144
145/// Helper attribute to build new derive macros. This replaces the standard
146/// library's `#[proc_macro_derive]` attribute.
147///
148/// Like [`proc_macro`](proc_macro_), it lets the annotated function take a
149/// single typed, [`Parse`](https://docs.rs/parsyng/latest/parsyng/parse/trait.Parse.html)-implementing argument —
150/// typically [`ast::item::DeriveInput`](https://docs.rs/parsyng/latest/parsyng/ast/item/type.DeriveInput.html)
151/// — and return any [`ToTokens`](https://docs.rs/parsyng/latest/parsyng/trait.ToTokens.html) value.
152///
153/// The attribute's argument names the derive trait, exactly as with the
154/// standard library's version: `#[parsyng::proc_macro_derive(MyTrait)]`.
155/// The optional `debug` argument is passed after a comma, as with
156/// `#[proc_macro_derive(MyTrait, attributes(...))]` in the standard library —
157/// here `#[parsyng::proc_macro_derive(MyTrait, debug)]` (see
158/// [`proc_macro`](proc_macro_) for what `debug` does).
159///
160/// # Example
161/// ```
162/// use parsyng::ast::item::DeriveInput;
163/// use parsyng::proc_macro::TokenStream;
164///
165/// # const IGNORE_TOKENS: &str = stringify! {
166/// #[parsyng::proc_macro_derive(MyTrait)]
167/// # };
168/// pub fn derive_my_trait(input: DeriveInput) -> TokenStream {
169/// let name = input.ident();
170/// parsyng::quote! {
171/// impl MyTrait for #name {}
172/// }
173/// }
174/// # let output = derive_my_trait(parsyng::parse_quote!(struct Foo;));
175/// # assert_eq!(output.to_string(), "impl MyTrait for Foo { }");
176/// ```
177// Export with an underscore, since it will conflicts with the `proc_macro_derive` builtin.
178#[proc_macro_attribute]
179pub fn proc_macro_derive_(args: TokenStream, input: TokenStream) -> TokenStream {
180 match proc_macro_derive_helper::proc_macro_derive(args, input) {
181 Ok(ok) => ok,
182 Err(err) => err.into_compile_error(),
183 }
184}
185
186/// Derives [`Parse`](https://docs.rs/parsyng/latest/parsyng/parse/trait.Parse.html) by parsing each field, in
187/// declaration order, with its own [`Parse`](https://docs.rs/parsyng/latest/parsyng/parse/trait.Parse.html)
188/// implementation.
189///
190/// Equivalent to writing, for `struct Foo { a: A, b: B }`:
191///
192/// ```
193/// # use parsyng::proc_macro::Ident;
194/// # struct Foo { a: u8, b: Ident }
195/// impl parsyng::parse::Parse for Foo {
196/// fn parse(input: &mut parsyng::parse::ParseBuffer) -> parsyng::error::Result<Self> {
197/// Ok(Self {
198/// a: input.parse()?,
199/// b: input.parse()?,
200/// })
201/// }
202/// }
203/// # let foo: Foo = parsyng::parse_quote!(1 x);
204/// # assert_eq!((foo.a, foo.b.to_string().as_str()), (1, "x"));
205/// ```
206///
207/// Tuple structs parse their fields positionally, and unit structs parse
208/// nothing. On an enum, each variant is tried in declaration order (without
209/// consuming any input on failure) and the first one that parses wins, so
210/// put more specific variants first; a unit variant always matches.
211/// Generic parameters and `where` clauses are carried over to the impl.
212///
213/// See [`macro@ToTokens`] for the complementary derive.
214#[proc_macro_derive(Parse)]
215pub fn derive_parse(input: TokenStream) -> TokenStream {
216 match derive_parse::derive_parse(input) {
217 Ok(ok) => ok,
218 Err(err) => err.into_compile_error(),
219 }
220}
221
222/// Derives [`ToTokens`](https://docs.rs/parsyng/latest/parsyng/trait.ToTokens.html) by appending each field's
223/// own tokens, in declaration order.
224///
225/// Equivalent to writing, for `struct Foo { a: A, b: B }`:
226///
227/// ```
228/// # use parsyng::proc_macro::Ident;
229/// # struct Foo { a: u8, b: Ident }
230/// impl parsyng::ToTokens for Foo {
231/// fn to_tokens(&self, tokens: &mut parsyng::proc_macro::TokenStream) {
232/// parsyng::ToTokens::to_tokens(&self.a, tokens);
233/// parsyng::ToTokens::to_tokens(&self.b, tokens);
234/// }
235/// }
236/// # let foo = Foo { a: 1, b: parsyng::format_ident!("x") };
237/// # assert_eq!(parsyng::ToTokens::to_token_stream(&foo).to_string(), "1u8 x");
238/// ```
239///
240/// Tuple structs emit their fields positionally, unit structs emit nothing,
241/// and an enum emits the fields of whichever variant it holds (the variant
242/// name itself is not emitted). Generic parameters and `where` clauses are
243/// carried over to the impl.
244///
245/// See [`macro@Parse`] for the complementary derive.
246#[proc_macro_derive(ToTokens)]
247pub fn derive_to_tokens(input: TokenStream) -> TokenStream {
248 match derive_to_tokens::derive_to_tokens(input) {
249 Ok(ok) => ok,
250 Err(err) => err.into_compile_error(),
251 }
252}