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
use crate::respan::{self, Respan};
use proc_macro2::{Delimiter, Group, Ident, Span, TokenStream, TokenTree};
use quote::{ToTokens, TokenStreamExt};
use std::collections::HashSet;
use std::env;
use std::fmt::{self, Display, Formatter, Write};
use syn::parse::Parse;
pub struct Quote {
tts: TokenStream,
span: Option<Box<(dyn Respan + 'static)>>,
sources: HashSet<Location>,
}
const INVALID_SPAN_STATE: &'static str = "Span is in invalid state.
Closure provided to push_group should not panic.";
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Location {
pub file_name: &'static str,
pub line: u32,
pub col: u32,
}
impl Display for Location {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}:{}:{}", self.file_name, self.line, self.col)?;
Ok(())
}
}
impl Quote {
pub fn new<S: Respan + 'static>(span: S) -> Self {
Quote {
span: Some(Box::new(span)),
tts: TokenStream::new(),
sources: Default::default(),
}
}
pub fn new_call_site() -> Self {
Self::new(Span::call_site())
}
pub fn from_tokens(tokens: &dyn ToTokens) -> Self {
Self::new(respan::FirstLast::from_tokens(tokens))
}
pub fn from_tokens_or<T: ToTokens>(tokens: &Option<T>, default_span: Span) -> Self {
match *tokens {
Some(ref tokens) => Self::from_tokens(tokens),
None => Self::new(default_span),
}
}
}
impl Quote {
pub fn parse<Node>(self) -> Node
where
Node: Parse,
{
let Quote { tts, sources, .. } = self;
let debug_tts = if env::var("DBG_DUMP").is_ok() {
Some(tts.clone())
} else {
None
};
syn::parse2(tts).unwrap_or_else(|err| {
let debug_tts: &dyn Display = match debug_tts {
Some(ref tts) => tts,
None => {
&"To get code failed to parse,
please set environment variable `DBG_DUMP` and run in again"
}
};
let notes = {
let mut b = String::from("Note: quasi quotting was invoked from:\n");
for src in &sources {
writeln!(b, " {}", src).unwrap();
}
b
};
panic!(
"Quote::parse() failed.
{notes}
Error from syn: {err}
>>>>>
{debug_tts}
<<<<<",
notes = notes,
err = err,
debug_tts = debug_tts
)
})
}
}
impl Quote {
#[doc(hidden)]
pub fn report_loc(&mut self, loc: Location) {
self.sources.insert(loc);
}
pub fn quote_with<F>(mut self, quote: F) -> Self
where
F: FnOnce(&mut Self),
{
(quote)(&mut self);
self
}
pub fn push_parsed(&mut self, token: &str) {
let Quote {
ref mut span,
ref mut tts,
..
} = *self;
token
.parse::<TokenStream>()
.expect("Failed to parse token to quote")
.into_iter()
.map(|tt| span.as_ref().expect(INVALID_SPAN_STATE).respan(tt))
.for_each(|tt| tts.append(tt));
}
pub fn push_tt(&mut self, tt: TokenTree) {
self.tts.append(tt)
}
pub fn push_sym(&mut self, term: &str) {
let span = self.next_span();
self.push_tt(TokenTree::Ident(Ident::new(term, span)))
}
fn next_span(&self) -> Span {
self.span.as_ref().expect(INVALID_SPAN_STATE).next_span()
}
pub fn push_group<F>(&mut self, delim: Delimiter, child: F)
where
F: FnOnce(&mut Quote),
{
let span = self.span.take().expect(INVALID_SPAN_STATE);
let mut sub = Quote::new(span);
child(&mut sub);
self.sources.extend(sub.sources);
debug_assert!(self.span.is_none());
self.span = Some(sub.span.expect(INVALID_SPAN_STATE));
self.push_tt(TokenTree::Group(Group::new(delim, sub.tts)))
}
pub fn push_tokens<T: ?Sized + ToTokens>(&mut self, node: &T) {
node.to_tokens(&mut self.tts);
}
}
impl IntoIterator for Quote {
type IntoIter = <TokenStream as IntoIterator>::IntoIter;
type Item = <TokenStream as IntoIterator>::Item;
fn into_iter(self) -> Self::IntoIter {
self.tts.into_iter()
}
}
impl From<Quote> for TokenStream {
fn from(quote: Quote) -> Self {
quote.tts
}
}
impl From<Quote> for proc_macro::TokenStream {
fn from(quote: Quote) -> Self {
TokenStream::from(quote).into()
}
}
impl ToTokens for Quote {
fn to_tokens(&self, dst: &mut TokenStream) {
self.tts.to_tokens(dst)
}
fn into_token_stream(self) -> TokenStream {
self.tts
}
}