1 | use crate::ToTokens; |
2 | use proc_macro2::extra::DelimSpan; |
3 | use proc_macro2::{Span, TokenStream}; |
4 | |
5 | // Not public API other than via the syn crate. Use syn::spanned::Spanned. |
6 | pub trait Spanned: private::Sealed { |
7 | fn __span(&self) -> Span; |
8 | } |
9 | |
10 | impl Spanned for Span { |
11 | fn __span(&self) -> Span { |
12 | *self |
13 | } |
14 | } |
15 | |
16 | impl Spanned for DelimSpan { |
17 | fn __span(&self) -> Span { |
18 | self.join() |
19 | } |
20 | } |
21 | |
22 | impl<T: ?Sized + ToTokens> Spanned for T { |
23 | fn __span(&self) -> Span { |
24 | join_spans(self.into_token_stream()) |
25 | } |
26 | } |
27 | |
28 | fn join_spans(tokens: TokenStream) -> Span { |
29 | #[cfg (not(needs_invalid_span_workaround))] |
30 | let mut iter: impl Iterator = tokens.into_iter().map(|tt: TokenTree| tt.span()); |
31 | |
32 | #[cfg (needs_invalid_span_workaround)] |
33 | let mut iter = tokens.into_iter().filter_map(|tt| { |
34 | let span = tt.span(); |
35 | let debug = format!(" {:?}" , span); |
36 | if debug.ends_with("bytes(0..0)" ) { |
37 | None |
38 | } else { |
39 | Some(span) |
40 | } |
41 | }); |
42 | |
43 | let first: Span = match iter.next() { |
44 | Some(span: Span) => span, |
45 | None => return Span::call_site(), |
46 | }; |
47 | |
48 | iter.fold(None, |_prev, next| Some(next)) |
49 | .and_then(|last| first.join(last)) |
50 | .unwrap_or(default:first) |
51 | } |
52 | |
53 | mod private { |
54 | use crate::ToTokens; |
55 | use proc_macro2::extra::DelimSpan; |
56 | use proc_macro2::Span; |
57 | |
58 | pub trait Sealed {} |
59 | impl Sealed for Span {} |
60 | impl Sealed for DelimSpan {} |
61 | impl<T: ?Sized + ToTokens> Sealed for T {} |
62 | } |
63 | |