vermouth 0.5.4

a new kind of parser for procedural macros
Documentation
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
//! See [`quote`](crate::quote!).

use proc_macro::{Punct, Spacing, Span, TokenStream};

// dawg i'm so tired of doing this
#[cfg(doc)]
use crate::{Verbatim, quote, verbatim};

use crate::{IntoTokens, TokenQueue};

/// Lazy quasi-quoting for Rust source.
///
/// See also [`Transcriber`] and [`TokenQueue`].
///
/// Returns a value (a [`Transcriber`]) implementing [`IntoTokens`] for use in extending a [`TokenQueue`].
///
/// The transcriber does not contain any tokens, but instead owns a closure which appends to a [`TokenQueue`].
///
/// # Interpolation
///
/// The rules for interpolation behave similarly to
/// [a `macro_rules!` transcriber](https://doc.rust-lang.org/nightly/reference/macros-by-example.html#r-macro.decl.transcription):
/// * `quote! { $foo }` inlines the contents of the variable `foo` into the evaluated token stream.
///   `foo` must implement [`IntoTokens`].
/// * `quote! { $$ }` evaluates to just `$`.
/// * unlike in `macro_rules!`, a lone `$` which might introduce ambiguity (e.g. `quote! { $ }`)
///   is always rejected.
///
/// This should be familiar if you have used
/// [the `quote` macro from David Tolnay's `quote` crate](https://docs.rs/quote/latest/quote/macro.quote.html),
/// but be aware that we use `$` rather than `#`, as our escape token.
///
/// # Token Fidelity and Verbatim Tokens
///
/// `quote` exploits compile-time introspection on token values to dramatically speed up transcription.
/// This, however, limits how tokens are transcribed in two ways.
///
/// Factoring out a call to the [`verbatim`] macro will solve both issues
/// by deferring to [`TokenStream::from_str`](TokenStream#impl-FromStr-for-TokenStream).
/// This comes at about an order-of-magnitude runtime cost for the token in question only.
///
/// ## 1. A very niche subset of valid tokens is rejected at compile time
///
/// In particular, custom numeric suffixes (`100u256`) and string prefixes (`w"foobar"`)
/// are supported by `verbatim` and not by `quote`, as is any yet-unreserved literal syntax.
/// For instance, the following fails to compile.
///
/// ```compile_fail
/// # vermouth::ඞ_declare_test!();
/// # use vermouth::quote;
/// quote! { let my_big_num = 100u256; }
/// # ;
/// ```
///
/// To work around this limitation, use the [`verbatim`] macro.
///
/// ```
/// # vermouth::ඞ_declare_test!();
/// # use vermouth::{quote, verbatim};
/// let v = verbatim!(100u256);
/// quote! { let my_big_num = $v; }
/// # ;
/// ```
///
/// Note that we explicitly support the edge case where a new type for literal values (e.g. [`f128`])
/// is added to the language and `vermouth` has not (yet 🤞) been updated to support it.
/// We use a compile-time switch to fall back to the same implementation as `verbatim`.
/// This is distinct from the cases above, where both `vermouth`
/// _and_ the Rust compiler fail to recognise a literal which is nevertheless syntactically valid.
///
/// See [the reference](https://doc.rust-lang.org/nightly/reference/tokens.html)
/// for the precise lexical structure of tokens in Rust today.
///
/// [`f128`]: https://github.com/rust-lang/rust/issues/116909
///
/// ## 2. Not all tokens are transcribed exactly as specified
///
/// Since we are limited by the methods which the standard library exposes,
/// we cannot currently guarantee the syntactic form of emitted literal tokens.
/// For example, the following two calls to `quote` are treated as if identical.
///
/// ```
/// # vermouth::ඞ_declare_test!();
/// # use vermouth::quote;
/// quote! { "foobar" }
/// # ;
/// quote! { r###"foobar"### }
/// # ;
/// ```
///
/// Note that we leverage the Rust compiler's literal parsing to ensure
/// that semantic meaning is always exactly preserved,
/// this is a purely syntactic and largely innocuous inconsistency.
/// For instance, `quote` _does_ guarantee that numeric literal suffixes will be respected.
///
/// ```
/// # vermouth::ඞ_declare_test!();
/// # use vermouth::quote;
/// // numeric literal with usize type:
/// quote! { 100usize }
/// # ;
/// // numeric literal with no specified type:
/// quote! { 100 }
/// # ;
/// ```
///
/// # Escaping `$$$`
///
/// Notably, while `$$` escapes `$`, the trifold `$$$` is not supported.
/// (This is merely a consequence of the linear-time `macro_rules!` implementation of `quote`).
///
/// ```compile_fail
/// # vermouth::ඞ_declare_test!();
/// # use vermouth::quote;
/// quote! {
///     let bills = stringify!($$$);
/// }
/// # ;
/// ```
///
/// Instead, try importing [`Dr`], which evaluates to `$`.
///
/// ```
/// # vermouth::ඞ_declare_test!();
/// # use vermouth::quote;
/// use vermouth::Dr;
/// quote! {
///     let bills = stringify!($Dr $Dr $Dr);
/// }
/// # ;
/// ```
#[cfg_attr(docsrs, doc(cfg(feature = "quote")))]
#[macro_export]
macro_rules! quote {
    ($($t:tt)*) => {
        $crate::Transcriber::from_fn(
            |_q| {
                #[allow(unused_imports)]
                use $crate::{IntoTokens as _, ඞ_macro_exports::{self as m, proc_macro, core, Spec, SpecLiteralQuote as _}};
                $crate::ඞ_macro_quote_extend_impl! { _q $({$t})* };
            },
        )
    };
}

/// A lazily-evaluated sequence of quoted tokens (what [`quote`] evaluates to).
///
/// See also [`quote`] and [`TokenQueue`].
///
/// [`Transcriber::from_fn`] can be used to manually construct a `Transcriber`, where one is required.
#[must_use = "`Transcriber`s are lazily evaluated. See `TokenQueue::extend_from`."]
#[derive(Clone, Copy)]
pub struct Transcriber<F> {
    f: F,
    span: Option<Span>,
}
impl<F> Transcriber<F>
where
    // NB: this doesn't stop us passing a `F: Fn(&mut TokenQueue)` since `Fn: FnMut: FnOnce`.
    F: FnOnce(&mut TokenQueue),
{
    /// Creates a new transcriber from a closure modifying a [`TokenQueue`].
    pub fn from_fn(f: F) -> Transcriber<F> {
        Transcriber { f, span: None }
    }

    /// Unwraps the closure backing this transcriber.
    pub fn into_fn(self) -> F {
        self.f
    }

    /// Annotates all tokens within the transcriber with the given span.
    ///
    /// ```
    /// # vermouth::ඞ_declare_test!();
    /// # use vermouth::{quote, TokenQueue};
    /// # use proc_macro::Span;
    /// #
    /// # let span = Span::call_site();
    /// # #[cfg(any())]
    /// let span: Span = omitted!();
    /// #
    /// let ref mut q = TokenQueue::new();
    /// q.extend_from(quote! { foo / bar }.with_span(span));
    /// ```
    ///
    /// See [`TokenQueue::set_tracked_span`] for more.
    pub fn with_span(mut self, span: Span) -> Transcriber<F> {
        self.span = Some(span);
        self
    }
}

impl<F> IntoTokens for Transcriber<F>
where
    F: FnOnce(&mut TokenQueue),
{
    fn extend_tokens(self, q: &mut TokenQueue) {
        if let Some(span) = self.span {
            q.set_tracked_span(span);
        }

        (self.f)(q);

        #[allow(clippy::redundant_pattern_matching, reason = "dude. lay off it.")]
        if let Some(_) = self.span {
            q.unset_tracked_span();
        }
    }
}

impl<F> From<Transcriber<F>> for TokenStream
where
    F: FnOnce(&mut TokenQueue),
{
    fn from(value: Transcriber<F>) -> TokenStream {
        TokenStream::from(value.into_tokens())
    }
}

/// The dollar doctor. Evaluates to `$`. Useful for escaping.
///
/// See [`quote`](quote#escaping-) for use cases.
#[derive(Debug, Clone, Copy)]
pub struct Dr;

impl IntoTokens for Dr {
    fn extend_tokens(self, q: &mut TokenQueue) {
        q.push(Punct::new('$', Spacing::Alone));
    }

    fn queue_size_hint(&self) -> (usize, Option<usize>) {
        (1, Some(1))
    }
}

/// Quotes a single token (either a literal, an identifier, or a lifetime) in exactly the format supplied.
///
/// Returns a value (a [`Verbatim`]) implementing [`IntoTokens`] for use in extending a [`TokenQueue`].
///
/// This macro expands the range of quotable tokens, at the cost of performance,
/// when compared to [`quote`].
/// See [the corresponding documentation](quote#token-fidelity-and-verbatim-tokens).
///
/// Note that we explicitly only support invoking `verbatim` on a single token at a time.
/// This is due to the unspecified nature of interactions between
/// [`TokenStream::from_str`](TokenStream#impl-FromStr-for-TokenStream) and [the `stringify` macro](stringify!).
/// We choose to marginalize the scope of possible breakage at the slight cost of expressivity.
#[cfg_attr(docsrs, doc(cfg(feature = "quote")))]
#[macro_export]
macro_rules! verbatim {
    ($lt:lifetime) => {
        $crate::Verbatim::new(
            $crate::ඞ_macro_exports::core::stringify!($lt),
            $crate::VerbatimKind::Lifetime,
        )
    };
    ($id:ident) => {
        $crate::Verbatim::new(
            $crate::ඞ_macro_exports::core::stringify!($lt),
            $crate::VerbatimKind::Ident,
        )
    };
    ($lit:literal) => {
        $crate::Verbatim::new(
            $crate::ඞ_macro_exports::core::stringify!($lt),
            $crate::VerbatimKind::Literal,
        )
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! ඞ_macro_quote_extend_impl {
    ($q:ident) => {};
    ($q:ident {$}) => {
        core::compile_error!("invalid quasi-quoting syntax: `$` cannot trail the input.");
    };
    ($q:ident $t:tt) => {
        $crate::ඞ_macro_quote_tt_impl! { $q $t };
    };
    ($q:ident {$} {$n:ident}) => {
        $n.extend_tokens($q);
    };
    ($q:ident $($t:tt)*) => {
        $crate::ඞ_macro_quote_parse_matrix! {
            ඞ_macro_quote_emit
            $q
            { _ _ _ _ _ $($t)* }
            { _ _ _ _ $($t)* _ }
            { _ _ _ $($t)* _ _ }
            { _ _ $($t)* _ _ _ }
            { _ $($t)* _ _ _ _ }
            { $($t)* _ _ _ _ _ }
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! ඞ_macro_quote_emit {
    (tt $q:ident $t:tt) => {
        $crate::ඞ_macro_quote_tt_impl! { $q $t };
    };
    (embed $q:ident $n:ident) => {
        $n.extend_tokens($q);
    };
    (rep $cx:tt $n:ident $($t:tt)*) => {
        core::compile_error!("i'm working on it trust bro");
    };
    (seprep $cx:tt $n:ident p:tt $($t:tt)*) => {
        core::compile_error!("i'm working on it trust bro");
    };
    (reserved $cx:tt $t:tt) => {
        core::compile_error!(core::concat!(
            "invalid quasi-quoting syntax: `",
            core::stringify!($t),
            "` following `@` is reserved.\n\
            help: use `@@` to quote a single `@` symbol.\n\
            help: see `vermouth::quote` for documentation.",
        ));
    };
    (triple_at $cx:tt) => {
        core::compile_error!("the syntax `@@@` is not supported by `vermouth::quote`.");
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! ඞ_macro_quote_parse_window {
    ($m:ident $cx:tt {$} {$} {$} $_3:tt $_4:tt $_5:tt) => {
        $crate::$m! { triple_at $cx }
    };
    ($m:ident $cx:tt {$} {$} $a:tt $b:tt $c:tt $d:tt) => {
        $crate::$m! { tt $cx {$} }
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ _ _ _ $a }
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ _ _ $a $b }
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ _ $a $b $c }
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ $a $b $c $d }
    };
    ($m:ident $cx:tt $_0:tt {$} {$n:ident} {($($t:tt)*)} {*} $a:tt) => {
        $crate::$m! { rep $cx $n $($t)* }
        $crate::ඞ_macro_quote_parse_window! { $q _ _ _ _ _ $a }
    };
    ($m:ident $cx:tt $_0:tt {$} {$n:ident} {($($t:tt)*)} {p:tt} {*}) => {
        $crate::$m! { seprep $cx $n p $($t)* }
    };
    ($m:ident $cx:tt $_0:tt {$} {$n:ident} $a:tt $b:tt $c:tt) => {
        $crate::$m! { embed $cx $n };
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ _ _ _ $a }
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ _ _ $a $b }
        $crate::ඞ_macro_quote_parse_window! { $m $cx _ _ _ $a $b $c }
    };
    ($m:ident $cx:tt $_0:tt {$} {$} $a:tt $b:tt $c:tt) => {};
    ($m:ident $cx:tt $_0:tt {$} $t:tt $_3:tt $_4:tt $_5:tt) => {
        $crate::$m! { reserved $cx $t }
    };
    ($m:ident $cx:tt $a:tt $b:tt {$} $_3:tt $_4:tt $_5:tt) => {
        $crate::ඞ_macro_quote_parse_window! { $m $cx $a $b _ _ _ _ }
    };
    ($m:ident $cx:tt $a:tt $b:tt $c:tt {$} $_4:tt $_5:tt) => {
        $crate::ඞ_macro_quote_parse_window! { $m $cx $a $b $c _ _ _ }
    };
    ($m:ident $cx:tt $a:tt $b:tt $c:tt $d:tt {$} $_5:tt) => {
        $crate::ඞ_macro_quote_parse_window! { $m $cx $a $b $c $d _ _ }
    };
    ($m:ident $cx:tt $a:tt $b:tt $c:tt $d:tt $e:tt {$}) => {
        $crate::ඞ_macro_quote_parse_window! { $m $cx $a $b $c $d $e _ }
    };
    ($m:ident $cx:tt $_0:tt $_1:tt $_2:tt $_3:tt $_4:tt $t:tt) => {
        $crate::$m! { tt $cx $t }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! ඞ_macro_quote_parse_matrix {
    (
        $m:ident
        $cx:tt
        { $($a:tt)* }
        { $($b:tt)* }
        { $($c:tt)* }
        { $($d:tt)* }
        { $($e:tt)* }
        { $($f:tt)* }
    ) => {
        $(
            $crate::ඞ_macro_quote_parse_window! { $m $cx $a $b $c $d $e $f }
        )*
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! ඞ_macro_quote_punct_seq {
    ($_:tt $($char:literal)+) => {
        &[
            $($char,)+
        ]
    };
}

/// Quotes a single token.
#[macro_export]
#[doc(hidden)]
macro_rules! ඞ_macro_quote_tt_impl {
    ($q:ident _) => {};
    ($q:ident {_}) => {
        m::push_underscore($q);
    };
    ($q:ident {()}) => {
        m::push_empty_group($q, proc_macro::Delimiter::Parenthesis);
    };
    ($q:ident {{}}) => {
        m::push_empty_group($q, proc_macro::Delimiter::Brace);
    };
    ($q:ident {[]}) => {
        m::push_empty_group($q, proc_macro::Delimiter::Bracket);
    };
    ($q:ident {($($t:tt)*)}) => {
        $crate::TokenQueue::open_substream($q);
        $crate::ඞ_macro_quote_extend_impl! { $q $({$t})* };
        $crate::TokenQueue::close_substream_and_push_as_group($q, proc_macro::Delimiter::Parenthesis);
    };
    ($q:ident {{$($t:tt)*}}) => {
        $crate::TokenQueue::open_substream($q);
        $crate::ඞ_macro_quote_extend_impl! { $q $({$t})* };
        $crate::TokenQueue::close_substream_and_push_as_group($q, proc_macro::Delimiter::Brace);
    };
    ($q:ident {[$($t:tt)*]}) => {
        $crate::TokenQueue::open_substream($q);
        $crate::ඞ_macro_quote_extend_impl! { $q $({$t})* };
        $crate::TokenQueue::close_substream_and_push_as_group($q, proc_macro::Delimiter::Bracket);
    };
    ($q:ident {$id:ident}) => {
        $crate::TokenQueue::push($q, const {
            m::parse_ident(stringify!($id))
        });
    };
    ($q:ident {$lit:literal}) => {
        m::Spec::new(&$lit).ඞ_lit_quote::<{ m::parse_lit_regime(core::stringify!($lit)) }>(
            &$lit,
            core::stringify!($lit),
            $q
        );
    };
    ($q:ident {$lt:lifetime}) => {
        $crate::TokenQueue::push($q, const {
            m::parse_lifetime(stringify!($lt))
        });
    };
    ($q:ident {$p:tt}) => {
        m::push_punct(
            $q,
            $crate::punct_decompose!(
                expand = $crate::ඞ_macro_quote_punct_seq,
                fallback = {
                    core::compile_error!(
                        core::concat!(
                            "unrecognised token: ",
                            core::stringify!($p),
                        )
                    );
                },
                $p
            )
        );
    };
}