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
#![no_std]
#![forbid(unsafe_code)]
//! Export tokens to other modules or crates. Now with 100% less proc macros!
//!
//! See the [integration tests](https://gitlab.com/konnorandrews/mini-macro-magic/-/tree/main/tests) for examples
//! that show *why* you would want to use [`export`].
//!
//! This crate provides the [`export`] macro which allows exporting tokens.
//! The concept is similar to that used by the inspiration for this crate [`macro_magic`](https://docs.rs/macro_magic/latest/macro_magic/).
//! Namely, a `macro_rules!` is generated. This `macro_rules!` will invoke a passed macro with the exported tokens.
//!
//! The difference to `macro_magic` is that this
//! crate does it all with one `macro_rules!` macro. No more need to poll in a set of proc macros
//! if you don't need the full power of `macro_magic`. Instead use [`export`] to generate a
//! macro you or a dependant crate can use. Also, a dependant crate doesn't need to know about
//! [`mini_macro_magic`][self] to use the generated `macro_rules!`. They are fully self contained.
//!
//! The [`export`] macro allows for a form of reflection. Reflection over the definition
//! of items by inspecting the tokens of the definition. `macro_rules` (and Rust macros
//! in general) have no way to eagerly expand their input. As a result [`export`] creates
//! a macro that you pass another macro call for it to expand into.
//!
//! ```
//! use mini_macro_magic::{export, emit};
//!
//! // Export the definition of `MyStruct`.
//! // Note without using `emit!()` `MyStruct` isn't actually created in this scope.
//! export!(
//!     #[export(my_struct$)]
//!     {
//!         struct MyStruct;
//!     }
//! );
//!
//! // An example macro that can parse a struct definition and get the name
//! // of the struct as a string.
//! macro_rules! name_of_struct {
//!     {{
//!         $(#[$($attr:tt)*])*
//!         $vis:vis struct $name:ident;
//!     }} => {
//!         stringify!($name)
//!     };
//! }
//!
//! // Invoke `name_of_struct` with the definition of `MyStruct`.
//! assert_eq!(my_struct!(name_of_struct!()), "MyStruct");
//! ```
//!
//! ## `#![no_std]`
//! [`mini_macro_magic`][self] is `#![no_std]`, it can be used anywhere Rust can.
//!
//! # Minimum Supported Rust Version
//!
//! Requires Rust 1.56.0.
//!
//! This crate follows the ["Latest stable Rust" policy](https://gist.github.com/alexheretic/d1e98d8433b602e57f5d0a9637927e0c). The listed MSRV won't be changed unless needed.
//! However, updating the MSRV anywhere up to the latest stable at time of release
//! is allowed.

/// Identity macro that just outputs what it is given.
///
/// This can be used with a [`export!()`] generated macro
/// to emit the exported tokens. See the [`example`] module for an example
/// of it's usage.
#[macro_export]
macro_rules! emit {
    {{$($t:tt)*}} => {$($t)*};
}

/// Export tokens for later inspection by other macros.
///
/// This macro enables exporting arbitrary token sequences to other
/// modules or even crates. Call the macro with the following form.
/// ```ignore
/// export!(
///     #[export(
///         /// Any extra docs you want.
///         <visibility> <macro name>$
///     )]
///     {
///         <some arbitrary tokens>
///     }
/// );
/// ```
/// This will generate a `macro_rules!` with the name given at `<macro name>`.
/// Any docs given in the `export` attribute will be added to the top of the macro
/// docs. The macro is already given a set of basic docs and an example (see [`example::demo_struct`]
/// for what this basic docs looks like).
///
/// `<visibility>` can be any of the normal visibility specifiers (nothing, `pub`, `pub(crate)`,
/// `pub(super)`, ...). It can also be `pub crate` which has a special meaning. `pub crate` is used
/// when in the root of a crate (`main.rs` or `lib.rs`) and we want the macro to be public outside
/// the crate. This is needed because the normal visibility specifiers don't work there.
///
/// The public visibility specifiers also automatically put the macro's docs in the module
/// [`export`] was invoked in instead of having the macro docs at the root of the crate.
///
/// The `$` after the macro name is always required. This is do to a limitation of `macro_ruiles!`
/// where `$` can't be escaped.
///
/// The form above was chossen because it allows code formatting to work as you would expect.
/// Any code in `<some arbitrary tokens>` is seen by rustfmt as a normal expression and can be
/// formatted accordingly. rustfmt will not format the `export` attribute though.
///
/// *Note:* The docs generated for the macro include a doc test example. The doc test should always
/// pass (if it doesn't please post an issue). However, sometimes this
/// may not be wanted. To disable the doc test generation (it will be generated as a text code
/// block instead) add the `mmm_no_gen_examples` cfg item (its not a feature) when compiling.
///
/// ### `macro_rules_attribute` Support
/// There is also another form [`export`] can be called with designed for use with the
/// [`macro_rules_attribute`](https://docs.rs/macro_rules_attribute/latest/macro_rules_attribute/) crate.
/// ```ignore
/// export!(
///     /// Any docs or attributes for the item (not the macro).
///     #[custom(export(
///         /// Any extra docs you want.
///         <visibility> <macro name>$
///     ))]
///     <some arbitrary tokens>
/// );
/// ```
/// When used with the [`macro_rules_attribute::derive`](https://docs.rs/macro_rules_attribute/latest/macro_rules_attribute/attr.derive.html) macro this allows the following.
/// ```
/// # use mini_macro_magic::export;
/// # use macro_rules_attribute::derive;
/// /// Some docs for `Demo`.
/// #[derive(export!)]
/// #[custom(export(
///     pub demo_struct$
/// ))]
/// struct Demo {
///     pub name: String,
/// }
/// ```
///
/// # Examples
///
/// See the [integration tests](https://gitlab.com/konnorandrews/mini-macro-magic/-/tree/main/tests) for examples
/// that show *why* you would want to use [`export`].
///
/// ```
/// # use mini_macro_magic::export;
/// export!(
///     #[export(
///         demo_struct$
///     )]
///     {
///         struct Demo {
///             pub name: String,
///         }
///     }
/// );
/// ```
///
/// ```
/// # use mini_macro_magic::export;
/// export!(
///     #[export(
///         pub a_plus_b$
///     )]
///     {
///         a + b
///     }
/// );
/// ```
///
/// ```
/// # use mini_macro_magic::export;
/// export!(
///     #[export(
///         /// Some docs.
///         pub(crate) allow_unused$
///     )]
///     {
///         #[allow(unused)]
///     }
/// );
/// ```
///
/// # Invalid Input
///
/// If [`export`] is called with incorrect syntax a compile error will be generated with the
/// expected calling syntax and the syntax it was given.
///
/// ```compile_fail
/// # use mini_macro_magic::export;
/// export!(
///     #[export(demo_struct)]
///     {
///         struct Demo {
///             pub name: String,
///         }
///     }
/// );
/// ```
/// ```text
/// error: `export!()` expects input of the form:
///       
///        #[export(<vis> <name>$)] { <tokens> }
///       
///        instead got:
///       
///        #[export(demo_struct)] { struct Demo { pub name : String, } }
///       
///   --> src/lib.rs:132:1
///    |
/// 6  | / export!(
/// 7  | |     #[export(demo_struct)]
/// 8  | |     {
/// 9  | |         struct Demo {
/// ...  |
/// 12 | |     }
/// 13 | | );
///    | |_^
/// ```
///
#[macro_export]
macro_rules! export {
    {
        #[export(
            $(#[$($attr:tt)*])*
            $name:ident $dollar:tt
        )]
        {
            $($t:tt)*
        }
    } => {
        $crate::__export_impl! {
            $(#[$($attr)*])*
            $name $dollar

            {
                use $name; // The standard use trick to make the macro an item.
            }

            {$($t)*}
        }
    };
    {
        #[export(
            $(#[$($attr:tt)*])*
            pub($($module:tt)*) $name:ident $dollar:tt
        )]
        {
            $($t:tt)*
        }
    } => {
        $crate::__export_impl! {
            $(#[$($attr)*])*
            $name $dollar

            {
                pub($($module)*) use $name; // The standard use trick to make the macro an item.
            }

            {$($t)*}
        }
    };
    {
        #[export(
            $(#[$($attr:tt)*])*
            pub $name:ident $dollar:tt
        )]
        {
            $($t:tt)*
        }
    } => {
        $crate::__export_impl! {
            $(#[$($attr)*])*
            #[doc(hidden)] // Hides the docs from the crate root.
            #[macro_export]
            $name $dollar

            // This makes the macro appear as a normal item with it's docs.
            {
                #[doc(inline)]
                pub use $name;
            }

            {$($t)*}
        }
    };
    {
        #[export(
            $(#[$($attr:tt)*])*
            pub crate $name:ident $dollar:tt
        )]
        {
            $($t:tt)*
        }
    } => {
        $crate::__export_impl! {
            $(#[$($attr)*])*
            #[macro_export]
            $name $dollar

            {} // A public macro at the crate root can't have a use.

            {$($t)*}
        }
    };
    {$($t:tt)*} => {
        // Assume all other invocations are using the derive form.
        //
        // If the syntax is wrong, then find_custom_export_attr will
        // emit a compile error.
        $crate::__find_custom_export_attr! { {} {$($t)*} }
    };
}

/// Unified impl for all the export macro variants.
#[doc(hidden)]
#[macro_export]
macro_rules! __export_impl {
    (
        // Any attributes for the macro.
        $(#[$($attr:tt)*])*

        // The name of the macro.
        $name:ident

        // Needed to inject the $ token into the generated macro_rules.
        $dollar:tt

        // The `use` statements wanted.
        {$($use:tt)*}

        // The actual tokens to export.
        {$($t:tt)*}
    ) => {
        $crate::__check_dollar!($dollar);

        $(#[$($attr)*])*
        ///
        /// Injects the exported tokens (see section below) into the given macro call.
        /// The exported tokens are injected in a `{}` block as the first thing.
        /// For example with `some_macro!(a + b)` the actual macro call would look like
        /// `some_macro!({ ... <exported tokens> ... } a + b)`.
        ///
        /// <details>
        /// <summary>Expand to show exported tokens</summary>
        ///
        /// *Note: The tokens here are formatted via [`stringify!()`] so may not be very
        /// readable.*
        ///
        /// ```text
        #[doc = stringify!($($t)*)]
        /// ```
        ///
        /// </details>
        ///
        /// # Examples
        ///
        #[cfg_attr(mmm_no_gen_examples, doc = "```text")]
        #[cfg_attr(not(mmm_no_gen_examples), doc = "```")]
        #[doc = concat!("use ", module_path!(), "::", stringify!($name), ";")]
        ///
        /// // Stringify all the exported tokens. The exported tokens are passed as a `{}`
        /// // block to `stringify!()` at the beginning.
        #[doc = concat!("let as_string = ", stringify!($name), "!(stringify!(some extra tokens));")]
        ///
        /// // Check that it matches what we expect.
        #[doc = concat!("assert_eq!(as_string, r#####\"", stringify!({$($t)*} some extra tokens), "\"#####);")]
        /// ```
        macro_rules! $name {
            ($dollar ($dollar t:tt)*) => {
                $crate::__invoke! { {} {$dollar ($dollar t)*} {$($t)*} }
            }
        }

        $($use)*
    };
}

/// TT muncher to find the path for a macro invocation.
///
/// `some::path::macro!(some stuff)`
/// this finds the `some::path::macro` and allows injecting extra tokens
/// as a `{ ... tokens ... }` as the first token of the invocation.
#[doc(hidden)]
#[macro_export]
macro_rules! __invoke {
    // `{<path>} {!(<arg tokens>)} {<extra tokens>}`
    //
    // This arm invokes the macro.
    ({$($path:tt)*} {!($($t:tt)*)} {$($extra:tt)*}) => {
        $($path)*!({$($extra)*} $($t)*);
    };
    // `{<path>} {![<arg tokens>]} {<extra tokens>}`
    //
    // This arm invokes the macro.
    ({$($path:tt)*} {![$($t:tt)*]} {$($extra:tt)*}) => {
        $($path)*![{$($extra)*} $($t)*];
    };
    // `{<path>} {!{<arg tokens>}} {<extra tokens>}`
    //
    // This arm invokes the macro.
    ({$($path:tt)*} {!{$($t:tt)*}} {$($extra:tt)*}) => {
        $($path)*!{ {$($extra)*} $($t)* }
    };
    // `{<part of path>} {<next token> <arg tokens>}} {<extra tokens>}`
    //
    // This arm recurses until it parses out the path.
    ({$($path:tt)*} {$next:tt $($t:tt)*} {$($extra:tt)*}) => {
        $crate::__invoke! { {$($path)* $next} {$($t)*} {$($extra)*} }
    };
}

/// Check that the passed in token is actually a literal `$`.
///
/// If it's not then a compile error is produced.
#[doc(hidden)]
#[macro_export]
macro_rules! __check_dollar {
    ($) => {};
    ($other:tt) => {compile_error! { concat!("`export!()` expects `$` after macro name, got `", stringify!($other), "`") }};
}

/// TT muncher to find the `#[custom(export(...))]` attribute.
#[doc(hidden)]
#[macro_export]
macro_rules! __find_custom_export_attr {
    ({$($attr:tt)*} {#[custom(export($($stuff:tt)*))] $($t:tt)*}) => {
        $crate::export! {
            #[export($($stuff)*)]
            {
                $($attr)*
                $($t)*
            }
        }
    };
    ({$($attr:tt)*} {$next:tt $($t:tt)*}) => {
        $crate::__find_custom_export_attr! {
            {$($attr)* $next}
            {$($t)*}
        }
    };
    ({$($a:tt)*} {$($t:tt)*}) => {
        compile_error! { concat!(
"`export!()` expects input of the form:

#[export(<vis> <name>$)] { <tokens> }

instead got:

",
stringify!($($a)* $($t)*),
"
\n")
        }
    }
}

/// Example of using [`export`] and [`emit`].
///
/// This module is not part of the crate's public API and is only visible on docs.
///
/// Code used for this module:
/// ```
/// pub mod example {
///     mini_macro_magic::export!(
///         #[export(
///             /// This is the macro generated by the example.
///             pub demo_struct$
///         )]
///         {
///             /// Demo struct definition.
///             pub struct Demo {
///                 /// The X value.
///                 pub x: i32,
///
///                 /// The Y value.
///                 pub y: i32,
///             }
///         }
///     );
///
///     // Emit the struct definition for Demo.
///     demo_struct!(mini_macro_magic::emit!());
/// }
/// ```
///
/// [`Demo`](example::Demo) is a struct definition exported by [`export`].
/// As you can see it exists as expected as a normal struct because we emitted
/// the tokens into the module with [`emit`].
///
/// [`demo_struct`] is the macro that was
/// generated by [`export`].
/// This is the macro you would call to inspect the tokens of [`Demo`](example::Demo).
#[cfg(doc_example)]
pub mod example {
    export!(
        #[export(
            /// This is the macro generated by the example.
            pub demo_struct$
        )]
        {
            /// Demo struct definition.
            pub struct Demo {
                /// The X value.
                pub x: i32,

                /// The Y value.
                pub y: i32,
            }
        }
    );

    // Emit the struct definition for Demo.
    demo_struct!(emit!());

    #[test]
    fn check_demo_exists() {
        let _x = Demo { x: 1, y: 2 };
    }
}

#[doc(hidden)]
#[cfg(not(doc_example))]
pub mod example {
    #[doc(hidden)]
    pub mod demo_struct {}
}