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
//! A trait for converting types composed of tokens into a [`TokenStream`].
//!
//! # The [`ToTokens`] trait
//! This trait provides a method of converting types into a [`TokenStream`].
//! This is primarily intended as a means of generating source code from a
//! syntax tree node.
//!
//! # [`quote`]
//! The API of this trait intentionally mirrors that of [`quote::ToTokens`],
//! and so should be familiar to users of that crate.

use std::sync::Arc;

use crate::scanner;
use crate::token::CarriageReturn;
use crate::token::Ident;
use crate::token::LitChar;
use crate::token::LitFloat;
use crate::token::LitInt;
use crate::token::LitStrDoubleQuote;
use crate::token::LitStrSingleQuote;
use crate::token::NewLine;
use crate::token::PunctKind;
use crate::token::SingleCharPunct;
use crate::token::Space2;
use crate::token::Space4;
use crate::token::Spacing;
use crate::token::Tab;
use crate::token::Token;
use crate::token::WhiteSpace;
use crate::Entry;
use crate::Span;
use crate::TokenStream;

/// A trait for converting types into a [`TokenStream`].
///
/// See the [module documentation][module] for more information.
///
/// [module]: (crate::to_tokens)
pub trait ToTokens {
    /// Append `self` to the given [`TokenStream`].
    fn to_tokens(&self, tokens: &mut TokenStream);

    /// Convert `self` directly into a [`TokenStream`].
    fn to_token_stream(&self) -> TokenStream {
        let mut tokens = TokenStream::new(vec![], None);
        self.to_tokens(&mut tokens);
        tokens
    }

    /// Convert `self` directly into a [`TokenStream`].
    fn into_token_stream(self) -> TokenStream
    where
        Self: Sized,
    {
        self.to_token_stream()
    }
}

impl<'a, T: ?Sized + ToTokens> ToTokens for &'a T {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        T::to_tokens(self, tokens);
    }

    fn to_token_stream(&self) -> TokenStream {
        T::to_token_stream(self)
    }
}

impl<'a, T: ?Sized + ToTokens> ToTokens for &'a mut T {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        T::to_tokens(self, tokens);
    }

    fn to_token_stream(&self) -> TokenStream {
        T::to_token_stream(self)
    }
}

impl<T: ToTokens> ToTokens for Option<T> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        if let Some(value) = self {
            value.to_tokens(tokens);
        }
    }

    fn to_token_stream(&self) -> TokenStream {
        self.as_ref()
            .map_or_else(|| TokenStream::new(vec![], None), ToTokens::to_token_stream)
    }

    fn into_token_stream(self) -> TokenStream {
        self.map_or_else(
            || TokenStream::new(vec![], None),
            ToTokens::into_token_stream,
        )
    }
}

impl ToTokens for TokenStream {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.tokens.append(&mut self.tokens.clone());
    }

    fn to_token_stream(&self) -> TokenStream {
        self.clone()
    }

    fn into_token_stream(self) -> TokenStream
    where
        Self: Sized,
    {
        self
    }
}

macro_rules! impl_nums {
    [$($ty:ty),* $(,)?] => {
        $(
            impl ToTokens for $ty {
                fn to_tokens(&self, tokens: &mut TokenStream) {
                    tokens.tokens.push(Entry::Ident(Ident::new(self.to_string(), Span::empty())));
                }
            }
        )*
    };
}

impl_nums![u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize, f32, f64];

impl ToTokens for str {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        LitStrDoubleQuote::new(self.to_string(), Span::empty()).to_tokens(tokens);
    }
}

impl ToTokens for String {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.as_str().to_tokens(tokens);
    }
}

fn str_to_tokens(string: &str, span: &Span, delimiter: PunctKind, tokens: &mut TokenStream) {
    let start_spacing = string.chars().next().map_or(Spacing::Joint, |ch| {
        if PunctKind::try_from(ch).is_ok() {
            Spacing::Joint
        } else {
            Spacing::Alone
        }
    });
    let start_span = Span::new(span.start, span.start + 1, Arc::clone(&span.source));
    let start = Entry::Punct(SingleCharPunct::new(delimiter, start_spacing, start_span));
    tokens.push(start);

    let (
        TokenStream {
            tokens: mut new_tokens,
            source: _,
        },
        _,
    ) = scanner::scan(Arc::clone(&span.source), span.start + 1, Some(span.end - 1));
    tokens.tokens.append(&mut new_tokens);

    let end_span = Span::new(span.end - 1, span.end, Arc::clone(&span.source));
    let end = Entry::Punct(SingleCharPunct::new(delimiter, Spacing::Alone, end_span));
    tokens.push(end);
}

impl ToTokens for LitStrDoubleQuote {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        str_to_tokens(self.string(), self.span(), PunctKind::DoubleQuote, tokens);
    }
}

impl ToTokens for LitStrSingleQuote {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        str_to_tokens(self.string(), self.span(), PunctKind::SingleQuote, tokens);
    }
}

impl ToTokens for LitChar {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let start_spacing = if PunctKind::try_from(self.ch()).is_ok() {
            Spacing::Joint
        } else {
            Spacing::Alone
        };
        let start_span = Span::new(
            self.span().start,
            self.span().start + 1,
            Arc::clone(&self.span().source),
        );
        let start = Entry::Punct(SingleCharPunct::new(
            PunctKind::SingleQuote,
            start_spacing,
            start_span,
        ));
        tokens.push(start);

        tokens.push(Entry::Ident(Ident::new(
            self.ch().to_string(),
            Span::empty(),
        )));

        let end_span = Span::new(
            self.span().end - 1,
            self.span().end,
            Arc::clone(&self.span().source),
        );
        let end = Entry::Punct(SingleCharPunct::new(
            PunctKind::SingleQuote,
            Spacing::Alone,
            end_span,
        ));
        tokens.push(end);
    }
}

impl ToTokens for Ident {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::Ident(self.clone()));
    }

    fn into_token_stream(self) -> TokenStream {
        let source = Arc::clone(&self.span.source);
        TokenStream::new(vec![Entry::Ident(self)], Some(source))
    }
}

impl ToTokens for LitInt {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::Ident(Ident::new(
            self.value().to_string(),
            self.span().clone(),
        )));
    }
}

impl ToTokens for LitFloat {
    #[allow(clippy::cast_sign_loss)] // There are no signed literals.
    fn to_tokens(&self, tokens: &mut TokenStream) {
        debug_assert!(self.value() >= 0.0, "literals must not be signed");
        let start = (self.value() - self.value().fract()).floor() as u64;
        let num_start_digits = start.checked_ilog10().unwrap_or(0) + 1;
        let mut fract = self.value().fract();
        while fract.fract() != 0.0 {
            fract *= 10.0;
        }
        let end = fract as u64;
        let num_end_digits = end.checked_ilog10().unwrap_or(0) + 1;
        tokens.push(Entry::Ident(Ident::new(
            start.to_string(),
            Span::new(
                self.span().start,
                self.span().start + num_start_digits as usize,
                Arc::clone(&self.span().source),
            ),
        )));
        tokens.push(Entry::Punct(SingleCharPunct::new(
            PunctKind::Dot,
            Spacing::Alone,
            Span::new(
                num_start_digits as usize,
                num_start_digits as usize + 1,
                Arc::clone(&self.span().source),
            ),
        )));
        tokens.push(Entry::Ident(Ident::new(
            end.to_string(),
            Span::new(
                self.span().end - num_end_digits as usize,
                self.span().end,
                Arc::clone(&self.span().source),
            ),
        )));
    }
}

impl ToTokens for WhiteSpace {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::WhiteSpace(self.clone()));
    }
}

impl ToTokens for Space2 {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::WhiteSpace(WhiteSpace::Space2(self.clone())));
    }
}

impl ToTokens for Space4 {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let start_span = Span::new(
            self.span.start,
            self.span.start + 2,
            Arc::clone(&self.span.source),
        );
        tokens.push(Entry::WhiteSpace(WhiteSpace::Space2(Space2 {
            span: start_span,
        })));
        let end_span = Span::new(
            self.span.end - 2,
            self.span.end,
            Arc::clone(&self.span.source),
        );
        tokens.push(Entry::WhiteSpace(WhiteSpace::Space2(Space2 {
            span: end_span,
        })));
    }
}

impl ToTokens for Tab {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::WhiteSpace(WhiteSpace::Tab(self.clone())));
    }
}

impl ToTokens for NewLine {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::WhiteSpace(WhiteSpace::NewLine(self.clone())));
    }
}

impl ToTokens for CarriageReturn {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.push(Entry::WhiteSpace(WhiteSpace::CarriageReturn(self.clone())));
    }
}