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
#![cfg_attr(feature = "nightly-doc", feature(external_doc))]
#![cfg_attr(feature = "nightly-doc", doc(include = "../README.md"))]

use pm::Span;
extern crate proc_macro;
use proc_macro2 as pm;
use quote::ToTokens;

mod bigint;
mod literal;

/// A stream of [`TokenTree`]s. This is typically what a proc macro will receive
#[derive(Debug, Clone)]
pub struct TokenStream {
    pub tokens: Vec<TokenTree>,
}

/// A single node in the token tree, i.e. a single token. May contain more
/// tokens via [`Group`].
#[derive(Debug, Clone)]
pub enum TokenTree {
    Group(Group),
    Ident(Ident),
    Punct(Punct),
    Literal(Literal),
}

pub use literal::{LitFloat, LitInt, LitKind, Literal};

/// A group of tokens, typically surrounded by [`Delimiter`]s.
#[derive(Debug, Clone)]
pub struct Group {
    pub stream: TokenStream,
    pub delimiter: Delimiter,
    /// The span of the entire group, including delimiters
    pub span: Span,
    /// The span of the opening delimiter
    pub span_open: Span,
    /// The span of the closing delimiter
    pub span_close: Span,
}

pub use pm::Delimiter;

/// An identifier
#[derive(Debug, Clone)]
pub struct Ident {
    pub span: Span,
    pub ident: String,
}

/// A punctuation token.
#[derive(Debug, Clone)]
pub struct Punct {
    pub kind: PunctKind,
    pub span: Span,
    /// Whether or not it is separated from the proceeding punctuation
    /// token by whitespace
    pub spacing: Spacing,
}

pub use pm::Spacing;

/// The specific kind of punctuation token
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum PunctKind {
    /// `;`
    Semicolon,
    /// `,`
    Comma,
    /// `.`
    Dot,
    /// `@`
    At,
    /// `~`
    Tilde,
    /// `?`
    Question,
    /// `:`
    Colon,
    /// `$`
    Dollar,
    /// `=`
    Eq,
    /// `!`
    Not,
    /// `<`
    Lt,
    /// `>`
    Gt,
    /// `-`
    Minus,
    /// `&`
    And,
    /// `|`
    Or,
    /// `+`
    Plus,
    /// `*`
    Star,
    /// `/`
    Slash,
    /// `^`
    Caret,
    /// `%`
    Percent,
}

pub trait AsNative {
    type Native;
    /// Convert an `absolution` token into its `proc_macro2` counterpart
    fn as_native(&self) -> Self::Native;
}

impl TokenTree {
    /// The span of this token tree
    pub fn span(&self) -> Span {
        match self {
            TokenTree::Group(ref g) => g.span,
            TokenTree::Ident(ref i) => i.span,
            TokenTree::Punct(ref p) => p.span,
            TokenTree::Literal(ref l) => l.span,
        }
    }
}

impl From<pm::TokenStream> for TokenStream {
    fn from(p: pm::TokenStream) -> Self {
        Self {
            tokens: p.into_iter().map(|t| t.into()).collect(),
        }
    }
}

impl From<proc_macro::TokenStream> for TokenStream {
    fn from(p: proc_macro::TokenStream) -> Self {
        let p: pm::TokenStream = p.into();
        p.into()
    }
}

impl AsNative for TokenStream {
    type Native = pm::TokenStream;
    fn as_native(&self) -> pm::TokenStream {
        self.tokens.iter().map(|t| t.as_native()).collect()
    }
}

impl From<pm::TokenTree> for TokenTree {
    fn from(p: pm::TokenTree) -> Self {
        match p {
            pm::TokenTree::Group(g) => TokenTree::Group(g.into()),
            pm::TokenTree::Ident(i) => TokenTree::Ident(i.into()),
            pm::TokenTree::Punct(p) => TokenTree::Punct(p.into()),
            pm::TokenTree::Literal(l) => TokenTree::Literal(l.into()),
        }
    }
}

impl AsNative for TokenTree {
    type Native = pm::TokenTree;
    fn as_native(&self) -> pm::TokenTree {
        match self {
            TokenTree::Group(ref g) => pm::TokenTree::Group(g.as_native()),
            TokenTree::Ident(ref i) => pm::TokenTree::Ident(i.as_native()),
            TokenTree::Punct(ref p) => pm::TokenTree::Punct(p.as_native()),
            TokenTree::Literal(ref l) => pm::TokenTree::Literal(l.as_native()),
        }
    }
}

impl From<pm::Group> for Group {
    fn from(p: pm::Group) -> Self {
        let span = p.span();
        let span_open = p.span_open();
        let span_close = p.span_close();
        let delimiter = p.delimiter();
        let stream = p.stream().into();
        Self {
            span,
            span_open,
            span_close,
            delimiter,
            stream,
        }
    }
}

impl AsNative for Group {
    type Native = pm::Group;
    fn as_native(&self) -> pm::Group {
        let mut g = pm::Group::new(self.delimiter, self.stream.as_native());
        g.set_span(self.span);
        g
    }
}

impl From<pm::Ident> for Ident {
    fn from(p: pm::Ident) -> Self {
        // XXXManishearth strip out and note down the r# of raw idents
        let span = p.span();
        let ident = p.to_string();
        Self { span, ident }
    }
}

impl AsNative for Ident {
    type Native = pm::Ident;
    fn as_native(&self) -> pm::Ident {
        pm::Ident::new(&self.ident, self.span)
    }
}

impl From<pm::Punct> for Punct {
    fn from(p: pm::Punct) -> Self {
        use PunctKind::*;
        let span = p.span();
        let spacing = p.spacing();

        let kind = match p.as_char() {
            ';' => Semicolon,
            ',' => Comma,
            '.' => Dot,
            '@' => At,
            '~' => Tilde,
            '?' => Question,
            ':' => Colon,
            '$' => Dollar,
            '=' => Eq,
            '!' => Not,
            '<' => Lt,
            '>' => Gt,
            '-' => Minus,
            '&' => And,
            '|' => Or,
            '+' => Plus,
            '*' => Star,
            '/' => Slash,
            '^' => Caret,
            '%' => Percent,
            x => panic!("Found unknown punctuation token: `{}`", x),
        };
        Self {
            kind,
            spacing,
            span,
        }
    }
}

impl AsNative for Punct {
    type Native = pm::Punct;
    fn as_native(&self) -> pm::Punct {
        pm::Punct::new(self.kind.as_char(), self.spacing)
    }
}

impl PunctKind {
    pub fn as_char(&self) -> char {
        use PunctKind::*;
        match *self {
            Semicolon => ';',
            Comma => ',',
            Dot => '.',
            At => '@',
            Tilde => '~',
            Question => '?',
            Colon => ':',
            Dollar => '$',
            Eq => '=',
            Not => '!',
            Lt => '<',
            Gt => '>',
            Minus => '-',
            And => '&',
            Or => '|',
            Plus => '+',
            Star => '*',
            Slash => '/',
            Caret => '^',
            Percent => '%',
        }
    }
}

macro_rules! totokens_impl {
    ($($ty:ident),+) => {
        $(
            impl ToTokens for $ty {
                fn to_tokens(&self, tokens: &mut pm::TokenStream) {
                    self.as_native().to_tokens(tokens)
                }
            }
        )+
    };
}

totokens_impl!(TokenStream, TokenTree, Group, Ident, Punct, Literal);