Skip to main content

moxy_token/bridge/
proc_macro.rs

1use crate::{Delim, Group, Ident, Keyword, LexError, Lit, Spacing, Span, ToTokens, TokenStream, TokenTree, TryIntoTokenStream};
2
3// --- Span (fallback) ---
4
5impl From<proc_macro::Span> for crate::span::fallback::Span {
6    fn from(#[allow(unused)] value: proc_macro::Span) -> Self {
7        #[cfg(nightly)]
8        {
9            let r = value.byte_range();
10            Self::new(r.start as u32, r.end as u32)
11        }
12
13        #[cfg(not(nightly))]
14        {
15            Self::default()
16        }
17    }
18}
19
20impl From<crate::span::fallback::Span> for proc_macro::Span {
21    fn from(_value: crate::span::fallback::Span) -> Self {
22        Self::call_site()
23    }
24}
25
26// --- Span ---
27
28impl From<proc_macro::Span> for Span {
29    #[inline]
30    fn from(value: proc_macro::Span) -> Self {
31        Self::Compiler(value)
32    }
33}
34
35impl From<Span> for proc_macro::Span {
36    fn from(value: Span) -> Self {
37        match value {
38            Span::Compiler(s) => s,
39            Span::Fallback(_) => Self::call_site(),
40        }
41    }
42}
43
44#[cfg(nightly)]
45impl proc_macro::MultiSpan for Span {
46    fn into_spans(self) -> Vec<proc_macro::Span> {
47        match self {
48            Self::Compiler(s) => vec![s],
49            Self::Fallback(_) => vec![proc_macro::Span::call_site()],
50        }
51    }
52}
53
54// --- Delim ---
55
56impl From<proc_macro::Delimiter> for Delim {
57    #[inline]
58    fn from(value: proc_macro::Delimiter) -> Self {
59        match value {
60            proc_macro::Delimiter::Parenthesis => Self::Paren,
61            proc_macro::Delimiter::Brace => Self::Brace,
62            proc_macro::Delimiter::Bracket => Self::Bracket,
63            proc_macro::Delimiter::None => Self::None,
64        }
65    }
66}
67
68impl From<Delim> for proc_macro::Delimiter {
69    #[inline]
70    fn from(value: Delim) -> Self {
71        match value {
72            Delim::Paren => Self::Parenthesis,
73            Delim::Brace => Self::Brace,
74            Delim::Bracket => Self::Bracket,
75            Delim::None => Self::None,
76        }
77    }
78}
79
80// --- Spacing ---
81
82impl From<proc_macro::Spacing> for Spacing {
83    #[inline]
84    fn from(value: proc_macro::Spacing) -> Self {
85        match value {
86            proc_macro::Spacing::Alone => Self::Alone,
87            proc_macro::Spacing::Joint => Self::Joint,
88        }
89    }
90}
91
92impl From<Spacing> for proc_macro::Spacing {
93    #[inline]
94    fn from(value: Spacing) -> Self {
95        match value {
96            Spacing::Alone => Self::Alone,
97            Spacing::Joint => Self::Joint,
98        }
99    }
100}
101
102// --- Ident ---
103
104impl From<proc_macro::Ident> for Ident {
105    #[inline]
106    fn from(value: proc_macro::Ident) -> Self {
107        Self::new(value.to_string()).with_span(value.span().into())
108    }
109}
110
111impl From<Ident> for proc_macro::Ident {
112    fn from(value: Ident) -> Self {
113        let span: proc_macro::Span = value.span().into();
114
115        if value.is_raw() {
116            Self::new_raw(value.text(), span)
117        } else {
118            Self::new(value.text(), span)
119        }
120    }
121}
122
123impl ToTokens for proc_macro::Ident {
124    fn to_tokens(&self, tokens: &mut TokenStream) {
125        let token = Ident::from(self.clone()).into_token_tree();
126        tokens.extend_one(token);
127    }
128}
129
130// --- Literal ---
131
132impl From<proc_macro::Literal> for Lit {
133    fn from(value: proc_macro::Literal) -> Self {
134        Self::from_repr(&value.to_string(), value.span().into())
135    }
136}
137
138impl From<Lit> for proc_macro::Literal {
139    fn from(value: Lit) -> Self {
140        let repr = value.repr();
141        let mut lit = repr.parse().unwrap_or_else(|_| Self::string(repr));
142
143        lit.set_span(value.span().into());
144        lit
145    }
146}
147
148impl ToTokens for proc_macro::Literal {
149    fn to_tokens(&self, tokens: &mut TokenStream) {
150        let token = Lit::from(self.clone()).into_token_tree();
151        tokens.extend_one(token);
152    }
153}
154
155// --- Group ---
156
157impl From<proc_macro::Group> for Group {
158    #[inline]
159    fn from(value: proc_macro::Group) -> Self {
160        use crate::span::DelimSpan;
161        let mut group = Self::new(value.delimiter().into(), value.stream().into());
162        group.span = DelimSpan::new(value.span_open().into(), value.span_close().into());
163        group
164    }
165}
166
167impl From<Group> for proc_macro::Group {
168    #[inline]
169    fn from(value: Group) -> Self {
170        let span = value.span.span().into();
171        let mut group = Self::new(value.delim.into(), value.tokens.into());
172        // `proc_macro::Group` accepts one span, so separate opening and
173        // closing delimiter spans are represented by their combined span.
174        group.set_span(span);
175        group
176    }
177}
178
179impl ToTokens for proc_macro::Group {
180    fn to_tokens(&self, tokens: &mut TokenStream) {
181        let token = Group::from(self.clone()).into_token_tree();
182        tokens.extend_one(token);
183    }
184}
185
186// --- TokenStream ---
187
188impl ToTokens<TokenStream> for proc_macro::TokenTree {
189    fn to_tokens(&self, tokens: &mut TokenStream) {
190        match self {
191            Self::Ident(v) => {
192                let span = v.span().into();
193                let text = v.to_string();
194                let tt = match text.as_str() {
195                    "true" => TokenTree::Literal(Lit::Bool(crate::LitBool::new(true, span))),
196                    "false" => TokenTree::Literal(Lit::Bool(crate::LitBool::new(false, span))),
197                    _ => match Keyword::from_str(&text, span) {
198                        Some(kw) => TokenTree::Keyword(kw),
199                        None => TokenTree::Ident(v.clone().into()),
200                    },
201                };
202                tokens.extend_one(tt)
203            }
204            Self::Literal(v) => tokens.extend_one(TokenTree::Literal(v.clone().into())),
205            Self::Group(v) => tokens.extend_one(TokenTree::Group(v.clone().into())),
206            Self::Punct(p) => crate::scan_puncts_spanned(&[(p.as_char(), p.span().into(), p.spacing().into())], tokens),
207        }
208    }
209}
210
211impl ToTokens<TokenStream> for proc_macro::TokenStream {
212    fn to_tokens(&self, tokens: &mut TokenStream) {
213        let mut punct_run: Vec<(char, Span, Spacing)> = Vec::new();
214
215        for tt in self.clone() {
216            match tt {
217                proc_macro::TokenTree::Punct(p) => punct_run.push((p.as_char(), p.span().into(), p.spacing().into())),
218                other => {
219                    if !punct_run.is_empty() {
220                        crate::scan_puncts_spanned(&punct_run, tokens);
221                        punct_run.clear();
222                    }
223                    other.to_tokens(tokens);
224                }
225            }
226        }
227
228        if !punct_run.is_empty() {
229            crate::scan_puncts_spanned(&punct_run, tokens);
230        }
231    }
232}
233
234impl ToTokens<proc_macro::TokenStream> for TokenTree {
235    fn to_tokens(&self, out: &mut proc_macro::TokenStream) {
236        match self {
237            Self::Group(g) => out.extend(vec![proc_macro::TokenTree::Group(g.clone().into())]),
238            Self::Ident(v) => out.extend(vec![proc_macro::TokenTree::Ident(v.clone().into())]),
239            Self::Keyword(kw) => {
240                let id = proc_macro::Ident::new(kw.as_str(), kw.span().into());
241                out.extend(vec![proc_macro::TokenTree::Ident(id)])
242            }
243            // `true`/`false` are identifiers to the compiler, not literals.
244            Self::Literal(Lit::Bool(v)) => {
245                let id = proc_macro::Ident::new(v.repr(), v.span().into());
246                out.extend(vec![proc_macro::TokenTree::Ident(id)])
247            }
248            Self::Literal(v) => out.extend(vec![proc_macro::TokenTree::Literal(v.clone().into())]),
249            Self::Punct(op) => {
250                let text = op.as_str();
251                let span: proc_macro::Span = op.span().into();
252                let last = text.chars().count() - 1;
253
254                for (i, ch) in text.chars().enumerate() {
255                    let spacing = if i == last {
256                        op.spacing().into()
257                    } else {
258                        proc_macro::Spacing::Joint
259                    };
260
261                    let mut p = proc_macro::Punct::new(ch, spacing);
262                    p.set_span(span);
263                    out.extend(vec![proc_macro::TokenTree::Punct(p)]);
264                }
265            }
266        }
267    }
268}
269
270impl ToTokens<proc_macro::TokenStream> for TokenStream {
271    fn to_tokens(&self, out: &mut proc_macro::TokenStream) {
272        for t in self.iter() {
273            t.to_tokens(out);
274        }
275    }
276}
277
278impl From<proc_macro::TokenStream> for TokenStream {
279    fn from(value: proc_macro::TokenStream) -> Self {
280        let mut out = Self::new();
281        value.to_tokens(&mut out);
282        out
283    }
284}
285
286impl From<TokenStream> for proc_macro::TokenStream {
287    fn from(value: TokenStream) -> Self {
288        let mut out = Self::new();
289
290        for t in value.iter() {
291            t.to_tokens(&mut out);
292        }
293
294        out
295    }
296}
297
298impl TryIntoTokenStream for proc_macro::TokenStream {
299    fn try_into_token_stream(self) -> Result<TokenStream, LexError> {
300        Ok(self.into())
301    }
302}
303
304impl TryIntoTokenStream for &proc_macro::TokenStream {
305    fn try_into_token_stream(self) -> Result<TokenStream, LexError> {
306        Ok(self.clone().into())
307    }
308}