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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// SPDX-License-Identifier: Apache-2.0 OR MIT
use quote::quote;
use syn::{
Expr, ExprAwait, ExprCall, ExprForLoop, ExprYield, Item, Token, parse_quote,
parse_quote_spanned,
spanned::Spanned as _,
visit_mut::{self, VisitMut},
};
use crate::{
parse, stream, stream_block, try_stream_block,
utils::{SliceExt as _, expr_compile_error, replace_expr, unit},
};
/// The scope in which `#[for_await]`, `.await`, or `yield` was called.
///
/// The type of coroutine depends on which scope is called.
#[derive(Clone, Copy, Default, PartialEq)]
pub(crate) enum Scope {
/// `async fn`, `async {}`, or `async ||`
#[default]
Future,
/// `#[stream]` (this)
Stream,
/// `#[try_stream]` (this)
TryStream,
/// `||`, `move ||`, or `static move ||`.
///
/// It cannot call `#[for_await]` or `.await` in this scope.
Closure,
/// `#[stream]` or `#[try_stream]` (other)
Other,
}
impl Scope {
fn is_stream(self) -> bool {
matches!(self, Self::Stream | Self::TryStream)
}
}
#[derive(Default)]
pub(crate) struct Visitor {
scope: Scope,
}
impl Visitor {
pub(crate) fn new(scope: Scope) -> Self {
Self { scope }
}
/// Visits `#[for_await] for <pat> in <expr> { .. }`.
pub(crate) fn visit_for_loop(&self, expr: &mut Expr) {
// Desugar
// from:
//
// #[for_await]
// <label> for <pat> in <e> {
// <body.stmts>
// }
//
// into:
//
// {
// let mut __pinned = <e>;
// let mut __pinned = unsafe { Pin::new_unchecked(&mut __pinned) };
// <label> loop {
// let <pat> = <match_next>;
// <body.stmts>
// }
// }
//
if let Expr::ForLoop(ExprForLoop { attrs, label, pat, expr: e, body, .. }) = expr {
match attrs.position_exact("for_await") {
Err(e) => {
*expr = expr_compile_error(&e);
return;
}
Ok(None) => return,
Ok(Some(i)) => {
attrs.remove(i);
}
}
let pinned = def_site_ident!("__pinned");
// It needs to adjust the type yielded by the macro because coroutines used internally by
// async fn yield `()` type, but coroutines used internally by `stream` yield
// `Poll<U>` type.
let match_next = match self.scope {
Scope::Future => {
quote! {
match ::futures_async_stream::__private::stream::next(&mut #pinned).await {
::futures_async_stream::__private::Some(e) => e,
::futures_async_stream::__private::None => break,
}
}
}
Scope::Stream | Scope::TryStream => {
let task_context = def_site_ident!("__task_context");
let poll_result = def_site_ident!("__poll_result");
quote! {{
let #poll_result = unsafe {
::futures_async_stream::__private::stream::Stream::poll_next(
::futures_async_stream::__private::Pin::as_mut(&mut #pinned),
::futures_async_stream::__private::future::get_context(
#task_context,
),
)
};
match #poll_result {
::futures_async_stream::__private::Poll::Ready(
::futures_async_stream::__private::Some(e),
) => e,
::futures_async_stream::__private::Poll::Ready(
::futures_async_stream::__private::None,
) => break,
::futures_async_stream::__private::Poll::Pending => {
#task_context =
yield ::futures_async_stream::__private::Poll::Pending;
continue;
}
}
}}
}
Scope::Closure => {
*expr = expr_compile_error(&format_err!(
&expr,
"for await may not be allowed outside of \
async blocks, functions, closures, async stream blocks, and functions",
));
return;
}
Scope::Other => unreachable!(),
};
body.stmts.insert(0, parse_quote!(let #pat = #match_next;));
*expr = parse_quote! {{
let mut #pinned = #e;
let mut #pinned = unsafe {
::futures_async_stream::__private::Pin::new_unchecked(&mut #pinned)
};
#label loop #body
}}
}
}
/// Visits `yield <expr>`.
fn visit_yield(&self, expr: &mut Expr) {
if !self.scope.is_stream() {
return;
}
// Desugar `yield <e>` into `__task_context = yield Poll::Ready(<e>)`.
if let Expr::Yield(ExprYield { yield_token, expr: e, .. }) = expr {
e.get_or_insert_with(|| Box::new(unit()));
let task_context = def_site_ident!("__task_context");
*expr = parse_quote! {
#task_context = #yield_token ::futures_async_stream::__private::Poll::Ready(#e)
};
}
}
/// Visits `stream_block!` macro.
fn visit_macro(&self, expr: &mut Expr) {
if self.scope != Scope::Other {
return;
}
replace_expr(expr, |expr| {
if let Expr::Macro(mut expr) = expr {
let mut e: ExprCall = if expr.mac.path.is_ident("stream_block") {
syn::parse(stream_block(expr.mac.tokens.into())).unwrap()
} else if expr.mac.path.is_ident("try_stream_block") {
syn::parse(try_stream_block(expr.mac.tokens.into())).unwrap()
} else {
return Expr::Macro(expr);
};
e.attrs.append(&mut expr.attrs);
Expr::Call(e)
} else {
unreachable!()
}
});
}
/// Visits `#[stream] async (move) <block>`.
fn visit_async(&self, expr: &mut Expr) {
if self.scope != Scope::Other {
return;
}
if let Expr::Async(e) = expr {
match (e.attrs.position_exact("stream"), e.attrs.position_exact("try_stream")) {
(Err(e), _) | (_, Err(e)) => {
*expr = expr_compile_error(&e);
}
(Ok(Some(_)), Ok(Some(i))) => {
*expr = expr_compile_error(&format_err!(
e.attrs.remove(i),
"#[stream] and #[try_stream] may not be used at the same time"
));
}
(Ok(Some(i)), _) => {
e.attrs.remove(i);
*expr = syn::parse2(stream::parse_async(e, parse::Context::Stream)).unwrap();
}
(_, Ok(Some(i))) => {
e.attrs.remove(i);
*expr = syn::parse2(stream::parse_async(e, parse::Context::TryStream)).unwrap();
}
(Ok(None), Ok(None)) => unreachable!(),
}
}
}
/// Visits `<base>.await`.
///
/// It needs to adjust the type yielded by the macro because coroutines used internally by
/// async fn yield `()` type, but coroutines used internally by `stream` yield
/// `Poll<U>` type.
fn visit_await(&self, expr: &mut Expr) {
if !self.scope.is_stream() {
return;
}
// Desugar `<base>.await` into:
//
// {
// let mut __pinned = <base>;
// let mut __pinned = unsafe { Pin::new_unchecked(&mut __pinned) };
// loop {
// if let Poll::Ready(result) = unsafe {
// Future::poll(Pin::as_mut(&mut __pinned), get_context(__task_context))
// } {
// break result;
// }
// __task_context = yield Poll::Pending;
// }
// }
if let Expr::Await(ExprAwait { base, await_token, .. }) = expr {
let task_context = def_site_ident!("__task_context");
// For interoperability with `forbid(unsafe_code)`, `unsafe` token should be call-site span.
let unsafety = <Token![unsafe]>::default();
*expr = parse_quote_spanned! { await_token.span() => {
let mut __pinned = #base;
let mut __pinned = #unsafety {
::futures_async_stream::__private::Pin::new_unchecked(&mut __pinned)
};
loop {
if let ::futures_async_stream::__private::Poll::Ready(result) = #unsafety {
::futures_async_stream::__private::future::Future::poll(
::futures_async_stream::__private::Pin::as_mut(&mut __pinned),
::futures_async_stream::__private::future::get_context(#task_context),
)
} {
break result;
}
#task_context = yield ::futures_async_stream::__private::Poll::Pending;
}
}};
}
}
}
impl VisitMut for Visitor {
fn visit_expr_mut(&mut self, expr: &mut Expr) {
// Backup current scope and adjust the scope. This must be done before visiting expr.
let tmp = self.scope;
match expr {
Expr::Async(expr)
if expr.attrs.iter().any(|attr| {
attr.path().is_ident("stream") || attr.path().is_ident("try_stream")
}) =>
{
self.scope = Scope::Other;
}
Expr::Async(_) => {
self.scope = Scope::Future;
}
Expr::Closure(expr) => {
self.scope = if expr.asyncness.is_some() { Scope::Future } else { Scope::Closure };
}
Expr::Macro(expr)
if expr.mac.path.is_ident("stream_block")
|| expr.mac.path.is_ident("try_stream_block") =>
{
self.scope = Scope::Other;
}
_ => {}
}
if self.scope != Scope::Other {
visit_mut::visit_expr_mut(self, expr);
}
match expr {
Expr::Async(_) => self.visit_async(expr),
Expr::Await(_) => self.visit_await(expr),
Expr::ForLoop(_) => self.visit_for_loop(expr),
Expr::Macro(_) => self.visit_macro(expr),
Expr::Yield(_) => self.visit_yield(expr),
_ => {}
}
// Restore the backup.
self.scope = tmp;
}
fn visit_item_mut(&mut self, _: &mut Item) {
// Do not recurse into nested items.
}
}