const_dispatch_proc_macros/
_mod.rs

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
//! Crate not intended for direct use.
//! Use https:://docs.rs/const-dispatch instead.
// Templated by `cargo-generate` using https://github.com/danielhenrymantilla/proc-macro-template
#![allow(nonstandard_style, unused_imports)]

use ::core::{
    mem,
    ops::Not as _,
};
use ::proc_macro::*;

macro_rules! tts {
    [
        $($tt:expr),* $(,)?
    ] => (
        [
            $(
                TokenTree::from($tt),
            )*
        ]
        .into_iter()
        .collect::<TokenStream>()
    );
}

#[proc_macro_attribute]
#[doc(hidden)] /** Not part of the public API */ pub
fn ඞexterminate(
    args: TokenStream,
    _input: TokenStream,
) -> TokenStream
{
    assert!(args.is_empty());
    TokenStream::new()
}

#[proc_macro_derive(ConstDispatch)] pub
fn __(
    input: TokenStream
) -> TokenStream
{
    let to_be_braced = Iterator::chain(
        tts![
            Punct::new('#', Spacing::Alone),
            Group::new(
                Delimiter::Bracket,
                tts![
                    Punct::new(':', Spacing::Joint),
                    Punct::new(':', Spacing::Alone),
                    Ident::new("const_dispatch", Span::mixed_site()),
                    Punct::new(':', Spacing::Joint),
                    Punct::new(':', Spacing::Alone),
                    Ident::new("ඞ", Span::mixed_site()),
                    Punct::new(':', Spacing::Joint),
                    Punct::new(':', Spacing::Alone),
                    Ident::new("exterminate", Span::mixed_site()),
                ]
            )
        ]
            .into_iter()
        ,
        input,
    );
    tts![
        Punct::new(':', Spacing::Joint),
        Punct::new(':', Spacing::Alone),
        Ident::new("const_dispatch", Span::mixed_site()),
        Punct::new(':', Spacing::Joint),
        Punct::new(':', Spacing::Alone),
        Ident::new("ඞ", Span::mixed_site()),
        Punct::new(':', Spacing::Joint),
        Punct::new(':', Spacing::Alone),
        Ident::new("derive_ConstDispatch", Span::mixed_site()),
        Punct::new('!', Spacing::Alone),
        Group::new(Delimiter::Brace, to_be_braced.collect()),
    ]
}

#[proc_macro]
#[doc(hidden)] /** Not part of the public API */ pub
fn ඞimpl_for_u8(
    _input: TokenStream,
) -> TokenStream
{
    // One-off helper macro.
    // Hygiene plays no role in the output, so we simplify the `syn`-less impl by using strings.
    let branches_const =
        (0..=u8::MAX)
            .map(|n| format!(r#"
                {n}_u8 => {{
                    const $C: ::core::primitive::u8 = $n;
                    {{
                        $crate::ඞ::try_hide!($scrutinee);
                        $body
                    }}
                }},
            "#))
            .collect::<String>()
    ;
    let branches_macro =
        (0..=u8::MAX)
            .map(|n| format!(r#"
                {n}_u8 => {{
                    $crate::ඞ::try_hide!($scrutinee);
                    __emit__! {{ $n }}
                }},
            "#))
            .collect::<String>()
    ;
    format!(r#"
        #[doc(hidden)]
        #[macro_export]
        macro_rules! u8 {{
            (
                $scrutinee:expr,
                |const $C:ident| $body:block
            ) => (
                match $scrutinee {{
                    {branches_const}
                }}
            );

            (
                $scrutinee:expr,
                $macro_input:tt => $macro_output:tt
            ) => ({{
                macro_rules! __emit__ {{ $macro_input => $macro_output }}
                match $scrutinee {{
                    {branches_macro}
                }}
            }});
        }}
    "#).parse().unwrap()
}

/// If `input = <identifier ≠ self>`, it emits a `let <identifier>: !;` to prevent the
/// `const`-dispatched code from accidently using the runtime value rather than the `const`.
#[proc_macro]
#[doc(hidden)] /** Not part of the public API */ pub
fn ඞtry_hide(
    input: TokenStream,
) -> TokenStream
{
    let ident = match input.into_iter().next().unwrap() {
        TokenTree::Group(g) if g.delimiter() == Delimiter::None => {
            let mut inner_tts = g.stream().into_iter();
            match (inner_tts.next(), inner_tts.next()) {
                (Some(TokenTree::Ident(ident)), None) if ident.to_string() != "self" => ident,
                _ => return <_>::default(),
            }
        },
        // currently not a reachable code path off a `$scrutinee:expr` arg, but who knows.
        TokenTree::Ident(ident) if ident.to_string() != "self" => ident,
        _ => return <_>::default(),
    };
    let allow_unused = Group::new(
        Delimiter::Bracket,
        tts![
            Ident::new("allow", Span::mixed_site()),
            Group::new(
                Delimiter::Parenthesis,
                tts![
                    Ident::new("unused", Span::mixed_site()),
                ],
            ),
        ],
    );
    tts![
        Punct::new('#', Spacing::Alone), allow_unused.clone(),
        // fn #ident() {}
        Ident::new("fn", Span::mixed_site()),
        ident.clone(),
        Group::new(Delimiter::Parenthesis, <_>::default()),
        Group::new(Delimiter::Brace, <_>::default()),

        Punct::new('#', Spacing::Alone), allow_unused,
        // let #ident: ::const_dispatch::ඞ::Never;
        Ident::new("let", Span::mixed_site()),
        ident,
        Punct::new(':', Spacing::Alone),

        Punct::new(':', Spacing::Joint),
        Punct::new(':', Spacing::Alone),
        Ident::new("const_dispatch", Span::mixed_site()),
        Punct::new(':', Spacing::Joint),
        Punct::new(':', Spacing::Alone),
        Ident::new("ඞ", Span::mixed_site()),
        Punct::new(':', Spacing::Joint),
        Punct::new(':', Spacing::Alone),
        Ident::new("Never", Span::mixed_site()),

        Punct::new(';', Spacing::Alone),
    ]
}