token-goblin-runtime 0.2.0

Runtime support types for token-goblin generated inline 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
//! Better UX for proc-macro.
//! Inspired by `crabtime`.
//!
//! Allows to receiving inputs and producing outputs in non `TokenStream` way.
//! This is the boring goblin craft: fewer raw token piles, more typed little bundles.
//!
//! E.g. instead of:
//! ```
//! # use proc_macro2::TokenStream;
//! # use syn::parse::Parser;
//!
//!
//! fn foo(input: TokenStream) -> TokenStream {
//!    let parser = syn::punctuated::Punctuated::<syn::LitStr, syn::Token![,]>::parse_terminated;
//!    let lit_components = parser.parse2(input).unwrap();
//!    let components = lit_components.iter().map(|c| c.value()).collect::<Vec<_>>();
//!    // Handling of `components`
//!    # todo!()
//! }
//! ```
//!
//! One could write:
//! ```
//! # use proc_macro2::TokenStream;
//! # use syn::parse::Parser;
//! # use token_goblin_runtime::prelude::*;
//!
//! fn foo(components: CommaSeparated<Token>) -> TokenStream {
//!    // Handling of `components`
//!    # todo!()
//! }
//! ```
//!
//! Since extending `syn::parse::Parse` with std types is not possible due to orphan rule.
//! We use macro `parse_into!`, that hardcodes checks for specific types.
//!
//! Note: having `String` and `Vec<String>` in input params remove span information, and reduce IDE/diagnostics quality.
//!
//! Output is a little bit more simple, it expected in three forms:
//! - `String` - For strings that should be converted to `TokenStream` without input span information
//! - `TokenStream` - as basic case.
//! - and in empty form - for cases where output is already emitted as `output_str!`, `output!` macros.
//!
//! So we have a trait `IntoTokenStream` that is solely focused on converting specific types into `TokenStream`.
//!
//! The user can extend it as well, to support custom types in output.

use core::fmt::{self, Display};
use std::{cell::RefCell, fmt::Debug, str::FromStr};

use proc_macro2::{Span, TokenStream};
use quote::ToTokens;
use syn::parse::{Parse, ParseStream, Parser};

/// Represents a single entry in `snif!` route.
///
/// Used to represent a single result of handled `snif!` macro.
///
/// Example:
/// ```no_build
/// #[derive(token_goblin::Snif)]
/// struct Foo {
///     x: i32,
/// }
///
/// token_goblin::snif!(Foo in stringify_our!()); // -> "Foo => { struct Foo { x : i32, } }" is one entry
/// ```
///
#[derive(Clone)]
pub struct SnifedEntry {
    /// Path to macro that was used to generate this entry.
    pub snif_path: syn::Path,
    arrow: syn::Token![=>],
    brace: syn::token::Brace,
    /// Item that was snifed.
    pub item: syn::Item,
}
/// Represents a group of `snif!` entries.
///
/// Used to represent a group of `snif!` entries in a macro.
///
/// Example:
/// ```no_build
///  token_goblin::snif!(Foo, Bar in stringify_our!("extra tokens"));
///  // -> "Foo => { struct Foo { x : i32, } }" is one entry
///  // "Bar => { struct Bar { x : i32, } }" is another
///  //
///  // "extra tokens" is passed to the macro as input.
/// ```
///
#[derive(Clone)]
pub struct SnifedEntries {
    first_group: syn::token::Bracket,
    pub entries: Vec<SnifedEntry>,
    second_group: syn::token::Bracket,
    pub macro_input: TokenStream,
}
impl SnifedEntries {
    #[must_use]
    pub fn span(&self) -> proc_macro2::Span {
        self.entries
            .first()
            .map_or_else(Span::call_site, SnifedEntry::span)
    }
}
impl SnifedEntry {
    #[must_use]
    pub fn span(&self) -> proc_macro2::Span {
        self.snif_path
            .segments
            .first()
            .map_or_else(Span::call_site, |segment| segment.ident.span())
    }
}
/// Represents a comma separated list of parsable values.
///
/// *A tidy little bundle of tokens, comma-sorted by the goblin before it hands them over.*
///
/// Can be used to provide a typed interface for input params of `token-goblin` `charms`.
///
/// Example:
/// ```no_build
/// #[token_goblin::munch]
/// fn foo(input: CommaSeparated<syn::LitStr>) -> TokenStream {
///     output_str!("{}", input.0.iter().map(|s| s.value()).collect::<Vec<_>>().join(", "));
/// }
///
/// foo!("foo", "bar", "baz");
/// // -> "foo, bar, baz"
/// ```
///
pub struct CommaSeparated<T>(pub Vec<T>);

impl From<CommaSeparated<Token>> for Vec<String> {
    fn from(value: CommaSeparated<Token>) -> Self {
        value.0.into_iter().map(|t| t.to_string()).collect()
    }
}

/// Represents either `Ident` or `LitStr` token.
///
/// *A bare ident or a quoted string - the goblin chews both the same.*
///
/// Used when macro need a simple interface for input, and user can decide a way to provide string.
///
/// Example:
/// ```no_build
/// #[token_goblin::munch]
/// fn foo(input: Token) -> TokenStream {
///     output_str!("{}", input.to_string());
/// }
///
/// foo!("foo");
/// // -> foo
///
pub enum Token {
    Ident(syn::Ident),
    Literal(syn::LitStr),
}
impl Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Token::Ident(ident) => write!(f, "{ident}"),
            Token::Literal(literal) => write!(f, "{}", literal.value()),
        }
    }
}

impl Debug for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Token::Ident(ident) => write!(f, "Ident({ident:?})"),
            Token::Literal(literal) => write!(f, "Literal({:?})", literal.value()),
        }
    }
}
impl PartialEq<&str> for Token {
    fn eq(&self, other: &&str) -> bool {
        match self {
            Token::Ident(ident) => ident == *other,
            // creates an owned string (but we don't have an api to compare directly)
            Token::Literal(literal) => literal.value() == *other,
        }
    }
}

#[doc(hidden)] // auto trait for FromTokenStream
pub trait TokenStreamInto<T> {
    fn convert_token_stream(self) -> syn::Result<T>;
}
impl<T: syn::parse::Parse> TokenStreamInto<T> for TokenStream {
    fn convert_token_stream(self) -> syn::Result<T> {
        T::parse.parse2(self)
    }
}

/// Convert specific type into `TokenStream`.
///
/// In `token-goblin` it is used to convert output types of `token-goblin` `charms` into `TokenStream`.
/// We provide default implementations for:
/// - `String`, `TokenStream`, `()` - so them can be used as output for `charm` fn
///   out of the box.
///
/// For `#[munch] mod {..}` user can provide custom implementation, to support custom types in output.
pub trait IntoTokenStream {
    fn into_token_stream(self) -> TokenStream;
}

impl IntoTokenStream for String {
    fn into_token_stream(self) -> TokenStream {
        TokenStream::from_str(&self).unwrap_or_else(|e| {
            compile_error(&format!("Failed to convert String to TokenStream: {e}"))
        })
    }
}
impl IntoTokenStream for TokenStream {
    fn into_token_stream(self) -> TokenStream {
        self
    }
}
impl IntoTokenStream for () {
    fn into_token_stream(self) -> TokenStream {
        TokenStream::new()
    }
}

fn compile_error(text: &str) -> TokenStream {
    quote::quote! {
        ::core::compile_error!(#text)
    }
}

/// Emit formatted string as token stream.
///
/// *The goblin's quick spit: hand it a string, it coughs up tokens.*
///
/// Example:
/// ```
/// # use token_goblin_runtime::prelude::*;
/// output_str!("foo + 2");
/// ```
///
/// This will spit `foo + 2` token stream (ident, punct, literal) as output of the macro, just before emitting result.
///
/// The format of input is the same as in `format!` macro.
///
/// Note: If input is invalid `TokenStream` this will emit compile error.
#[macro_export]
macro_rules! output_str {
    ($($tokens:tt)*) => {
        $crate::ux::push_output(format!($($tokens)*));
    };
}

/// Emit quote as token stream.
///
/// Example:
/// ```
/// # use token_goblin_runtime::prelude::*;
/// output! {
///     foo + bar
/// };
/// ```
///
/// This will spit quoted `TokenStream` as output of the macro, just before emitting result.
/// The format of input is the same as in `quote!` macro.
///
/// Note: that this is different from `output_str!` macro:
/// ```
/// # use token_goblin_runtime::prelude::*;
/// output_str!("foo + 2");
/// output! {
///     "foo + 2"
/// };
/// ```
///
/// The first will emit `foo + 2` token stream (ident, punct, literal) as output of the macro.
/// But the second one will emit `"foo + 2"` as string literal.
///
#[macro_export]
macro_rules! output {
    ($($tokens:tt)*) => {
        $crate::ux::push_output($crate::prelude::quote!($($tokens)*));
    };
}

thread_local! {
    static COLLECTED_OUTPUT: RefCell<TokenStream> = RefCell::new(TokenStream::new());
}

/// For some usages, user might want to emit output streamingly, like `println!` or `write!` macros.
///
/// This function is internall implementation of this feature, it's recommended to use:
/// `output!`, or `output_str!` macros instead.
pub fn push_output(output: impl IntoTokenStream) {
    COLLECTED_OUTPUT.with(|collected_output| {
        collected_output
            .borrow_mut()
            .extend(output.into_token_stream());
    });
}

#[doc(hidden)]
#[must_use]
pub(crate) fn flush_output(last_part: TokenStream) -> TokenStream {
    COLLECTED_OUTPUT.with(|collected_output| {
        let mut collected_output = std::mem::take(&mut *collected_output.borrow_mut());
        collected_output.extend(last_part);
        collected_output
    })
}

impl Parse for Token {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        if input.peek(syn::Ident) {
            Ok(Token::Ident(input.parse()?))
        } else if input.peek(syn::LitStr) {
            Ok(Token::Literal(input.parse()?))
        } else {
            Err(syn::Error::new(input.span(), "Expected ident or literal"))
        }
    }
}

impl<T: Parse> Parse for CommaSeparated<T> {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let parser = syn::punctuated::Punctuated::<T, syn::Token![,]>::parse_terminated;
        let components = parser(input)?;
        Ok(CommaSeparated(components.into_iter().collect()))
    }
}

impl syn::parse::Parse for SnifedEntry {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        // Skip ident + `::`, find `=>` in tokenstream. then feed bounded stream into `syn::Path::parse`

        let path = syn::Path::parse_mod_style(input)?;

        let arrow = input.parse()?;

        let content;
        let brace = syn::braced!(content in input);
        let item = content.parse()?;

        Ok(SnifedEntry {
            snif_path: path,
            arrow,
            brace,
            item,
        })
    }
}
impl syn::parse::Parse for SnifedEntries {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let items_input;
        let first_group = syn::bracketed!(items_input in input);
        let mut items = Vec::new();
        while !items_input.is_empty() {
            items.push(SnifedEntry::parse(&items_input)?);
        }
        let macro_input;
        let second_group = syn::bracketed!(macro_input in input);

        Ok(SnifedEntries {
            first_group,
            entries: items,
            second_group,
            macro_input: macro_input.parse()?,
        })
    }
}
impl ToTokens for SnifedEntry {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.snif_path.to_tokens(tokens);
        self.arrow.to_tokens(tokens);
        self.brace.surround(tokens, |tokens| {
            self.item.to_tokens(tokens);
        });
    }
}
impl ToTokens for SnifedEntries {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.first_group.surround(tokens, |tokens| {
            for item in &self.entries {
                item.to_tokens(tokens);
            }
        });
        self.second_group.surround(tokens, |tokens| {
            self.macro_input.to_tokens(tokens);
        });
    }
}
#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn test_parse_string() {
        let tokens = TokenStream::from_str(" \"123\" ").unwrap();
        let into: Token = tokens.convert_token_stream().unwrap();
        assert_eq!(into.to_string(), "123");
    }
    #[test]
    fn test_parse_vec() {
        let tokens = TokenStream::from_str(" \"1\", \"2\", \"3\" ").unwrap();
        let into: CommaSeparated<Token> = tokens.convert_token_stream().unwrap();
        assert_eq!(into.0, vec!["1", "2", "3"]);
    }

    #[test]
    fn test_parse_tts() {
        let tokens = TokenStream::from_str("123").unwrap();
        let into: TokenStream = tokens.clone().convert_token_stream().unwrap();
        assert_eq!(into.to_string(), tokens.to_string());
    }

    #[test]
    fn test_parse_syn_type() {
        let tokens = TokenStream::from_str("asd").unwrap();
        let into: syn::Ident = tokens.convert_token_stream().unwrap();
        assert_eq!(into.to_string(), "asd");
    }

    #[test]
    fn test_streaming_output() {
        output_str!("foo");
        output_str!("bar");
        output! {
            "baz" // quote will emit tokens so this becumes string literal
        };
        let output = flush_output(TokenStream::from_str("qux").unwrap());
        assert_eq!(output.to_string(), "foo bar \"baz\" qux");
    }
}