easy_ext/
to_tokens.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use std::iter;
4
5use proc_macro::{Group, Ident, Punct, TokenStream, TokenTree};
6
7pub(crate) trait ToTokens {
8    fn to_tokens(&self, tokens: &mut TokenStream);
9
10    fn to_token_stream(&self) -> TokenStream {
11        let mut tokens = TokenStream::new();
12        self.to_tokens(&mut tokens);
13        tokens
14    }
15}
16
17impl ToTokens for Ident {
18    fn to_tokens(&self, tokens: &mut TokenStream) {
19        tokens.extend(iter::once(TokenTree::Ident(self.clone())));
20    }
21}
22
23impl ToTokens for Punct {
24    fn to_tokens(&self, tokens: &mut TokenStream) {
25        tokens.extend(iter::once(TokenTree::Punct(self.clone())));
26    }
27}
28
29impl ToTokens for Group {
30    fn to_tokens(&self, tokens: &mut TokenStream) {
31        tokens.extend(iter::once(TokenTree::Group(self.clone())));
32    }
33}
34
35impl ToTokens for TokenTree {
36    fn to_tokens(&self, tokens: &mut TokenStream) {
37        tokens.extend(iter::once(self.clone()));
38    }
39}
40
41impl ToTokens for TokenStream {
42    fn to_tokens(&self, tokens: &mut TokenStream) {
43        tokens.extend(self.clone());
44    }
45}
46
47impl<T: ToTokens> ToTokens for Option<T> {
48    fn to_tokens(&self, tokens: &mut TokenStream) {
49        if let Some(t) = self {
50            T::to_tokens(t, tokens);
51        }
52    }
53}
54
55impl<T: ?Sized + ToTokens> ToTokens for &T {
56    fn to_tokens(&self, tokens: &mut TokenStream) {
57        T::to_tokens(self, tokens);
58    }
59}
60
61impl<T: ToTokens> ToTokens for [T] {
62    fn to_tokens(&self, tokens: &mut TokenStream) {
63        for t in self {
64            T::to_tokens(t, tokens);
65        }
66    }
67}
68
69impl<T: ToTokens> ToTokens for [(T, Option<Punct>)] {
70    fn to_tokens(&self, tokens: &mut TokenStream) {
71        for (t, p) in self {
72            T::to_tokens(t, tokens);
73            p.to_tokens(tokens);
74        }
75    }
76}