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
use proc_macro2::{Span, TokenStream, TokenTree};
use quote::ToTokens;
use std::cell::Cell;
pub trait Respan {
fn next_span(&self) -> Span;
fn respan(&self, mut tt: TokenTree) -> TokenTree {
let span = self.next_span();
match tt {
TokenTree::Group(ref mut tt) => tt.set_span(span),
TokenTree::Ident(ref mut tt) => tt.set_span(span),
TokenTree::Punct(ref mut tt) => tt.set_span(span),
TokenTree::Literal(ref mut tt) => tt.set_span(span),
}
tt
}
}
impl Respan for Span {
fn next_span(&self) -> Span {
*self
}
}
impl<'a, S> Respan for &'a S
where
S: ?Sized + Respan,
{
fn next_span(&self) -> Span {
<S as Respan>::next_span(self)
}
}
impl<S> Respan for Box<S>
where
S: ?Sized + Respan,
{
fn next_span(&self) -> Span {
<S as Respan>::next_span(self)
}
}
#[derive(Debug, Clone)]
pub struct FirstLast {
first: Cell<Option<Span>>,
last: Span,
}
impl Respan for FirstLast {
fn next_span(&self) -> Span {
self.first.take().unwrap_or(self.last)
}
}
impl FirstLast {
pub fn from_tokens(tokens: &dyn ToTokens) -> Self {
let mut spans = TokenStream::new();
tokens.to_tokens(&mut spans);
let good_tokens = TokenStream::from(spans).into_iter().collect::<Vec<_>>();
let first_span = good_tokens
.first()
.map(|t| t.span())
.unwrap_or(Span::call_site());
let last = good_tokens.last().map(|t| t.span()).unwrap_or(first_span);
FirstLast {
first: Cell::new(Some(first_span)),
last,
}
}
}