1use crate::access::{Set, mentions};
14use crate::classify::{Class, Exits, Node, Scope, classify, line_of};
15use crate::effects::{Target, value_target};
16use crate::schedule::{emit, plan};
17use crate::{Options, Report, hoist};
18use quote::{ToTokens, format_ident};
19use syn::{Block, Expr, Local, Stmt, spanned::Spanned, visit_mut::VisitMut};
20
21const MAX_HOIST_DEPTH: usize = 8;
23
24pub(crate) struct Rewriter<'a> {
26 pub options: &'a Options,
27 pub scope: Scope,
29 pub report: Report,
31 pub in_async: bool,
33 pub fresh: usize,
35 pub refusal: Option<String>,
37 pub loop_check: String,
39 pub loop_lines: Vec<(usize, usize)>,
41}
42
43impl VisitMut for Rewriter<'_> {
44 fn visit_expr_async_mut(&mut self, e: &mut syn::ExprAsync) {
45 let outer = std::mem::replace(&mut self.in_async, true);
47 let outer_sync = std::mem::replace(&mut self.scope.sync, false);
48 syn::visit_mut::visit_expr_async_mut(self, e);
49 self.in_async = outer;
50 self.scope.sync = outer_sync;
51 }
52
53 fn visit_expr_closure_mut(&mut self, e: &mut syn::ExprClosure) {
54 let outer = std::mem::replace(&mut self.in_async, e.asyncness.is_some());
55 let outer_sync = std::mem::replace(&mut self.scope.sync, false);
56 syn::visit_mut::visit_expr_closure_mut(self, e);
57 self.in_async = outer;
58 self.scope.sync = outer_sync;
59 }
60
61 fn visit_item_mut(&mut self, _: &mut syn::Item) {}
63
64 fn visit_block_mut(&mut self, block: &mut Block) {
65 let mut stmts = Vec::with_capacity(block.stmts.len());
66 for mut stmt in std::mem::take(&mut block.stmts) {
67 match &mut stmt {
68 Stmt::Expr(Expr::ForLoop(f), semi)
73 if self.in_async && !self.scope.sync && self.rewrites_loops() =>
74 {
75 self.visit_expr_mut(&mut f.expr);
76 if let Some(rewritten) = self.rewrite_loop(f) {
77 stmts.push(Stmt::Expr(rewritten, *semi));
78 continue;
79 }
80 self.visit_block_mut(&mut f.body);
81 }
82 Stmt::Expr(Expr::While(w), semi)
83 if self.in_async && !self.scope.sync && self.rewrites_loops() =>
84 {
85 if let Some(rewritten) = self.rewrite_while(w) {
86 stmts.push(Stmt::Expr(rewritten, *semi));
87 continue;
88 }
89 self.visit_stmt_mut(&mut stmt);
90 }
91 _ => self.visit_stmt_mut(&mut stmt),
92 }
93 stmts.push(stmt);
94 }
95 block.stmts = if self.in_async {
96 self.rewrite_stmts(stmts)
97 } else {
98 stmts
99 };
100 }
101}
102
103impl Rewriter<'_> {
104 fn rewrites_loops(&self) -> bool {
106 self.options.baseline != Some(crate::Baseline::Resync)
107 }
108
109 pub(crate) fn next(&mut self) -> usize {
111 self.fresh += 1;
112 self.fresh
113 }
114
115 fn rewrite_stmts(&mut self, stmts: Vec<Stmt>) -> Vec<Stmt> {
117 let tail_hoisted = self.hoist_tail(stmts.clone());
118 let exposed = self.expose_awaits(tail_hoisted);
119 let before = self.report.regions.len();
120 let out = self.schedule_block(exposed);
121 if self.report.regions[before..].iter().any(|r| r.changed) {
122 out
123 } else {
124 stmts
125 }
126 }
127
128 fn hoist_tail(&mut self, mut stmts: Vec<Stmt>) -> Vec<Stmt> {
131 let Some(Stmt::Expr(tail, None)) = stmts.last() else {
132 return stmts;
133 };
134 let as_statement = Stmt::Expr(tail.clone(), Some(Default::default()));
135 let movable =
136 matches!(classify(&as_statement, &self.scope, false), Class::Node(ref n) if !n.effect);
137 if Exits::of(tail).awaits && movable {
138 let value = tail.clone();
139 let name = format_ident!("__psync_t{}", self.next());
140 stmts.pop();
141 stmts.push(syn::parse_quote_spanned!(value.span()=> let #name = #value;));
142 stmts.push(Stmt::Expr(syn::parse_quote!(#name), None));
143 }
144 stmts
145 }
146
147 fn expose_awaits(&mut self, stmts: Vec<Stmt>) -> Vec<Stmt> {
152 let mut out = Vec::with_capacity(stmts.len());
153 let mut work: Vec<(Stmt, usize)> = stmts.into_iter().rev().map(|s| (s, 0)).collect();
154 while let Some((stmt, depth)) = work.pop() {
155 let hides_await = match classify(&stmt, &self.scope, false) {
156 Class::Node(n) => n.awaits && (n.effect || !awaited_value(&stmt)),
159 Class::Barrier(_) => Exits::of_stmt(&stmt).awaits,
160 };
161 if hides_await && depth < MAX_HOIST_DEPTH {
162 let n = self.next();
163 let split = hoist::scrutinee(&stmt, n)
164 .map(|(value, rest)| (vec![value], rest))
165 .or_else(|| hoist::operands(&stmt, &mut self.fresh))
166 .or_else(|| {
168 self.rewrites_loops()
169 .then(|| self.hoist_branch(&stmt))
170 .flatten()
171 .map(|(g, rest)| (vec![g], rest))
172 });
173 if let Some((values, rest)) = split {
174 work.push((rest, depth + 1));
175 work.extend(values.into_iter().rev().map(|v| (v, depth + 1)));
176 continue;
177 }
178 }
179 out.push(stmt);
180 }
181 out
182 }
183
184 fn schedule_block(&mut self, stmts: Vec<Stmt>) -> Vec<Stmt> {
186 let mentions: Vec<Set> = stmts
187 .iter()
188 .map(|s| mentions(s.to_token_stream()))
189 .collect();
190 let mut out = Vec::new();
191 let mut region: Vec<(usize, Node)> = Vec::new();
192 let last = stmts.len().saturating_sub(1);
193 let mut values: std::collections::HashMap<String, Target> = Default::default();
196 for (index, stmt) in stmts.into_iter().enumerate() {
197 let class = if index == last && matches!(stmt, Stmt::Expr(_, None)) {
199 let generated = stmt.to_token_stream().to_string().contains("__psync");
202 let awaits = Exits::of_stmt(&stmt).awaits && !generated;
203 Class::Barrier(
204 awaits.then(|| format!("line {}: the block's value", line_of(stmt.span()))),
205 )
206 } else {
207 classify(&stmt, &self.scope, false)
208 };
209 let class = match class {
210 Class::Node(mut n) => {
211 let inner = crate::classify::inner_bindings(&n.stmt);
212 for e in &mut n.effects {
213 if let Some(name) = e.target.single_name()
214 && !inner.contains(name)
215 && let Some(t) = values.get(name)
216 {
217 e.target = t.clone();
218 }
219 }
220 Class::Node(n)
221 }
222 barrier => barrier,
223 };
224 let class = match class {
227 Class::Node(_) if !self.rewrites_loops() && is_control_flow(&stmt) => {
228 Class::Barrier(None)
229 }
230 class => class,
231 };
232 bind_values(&mut values, &stmt, &self.scope.mutable);
233 match class {
234 Class::Node(n) => region.push((index, *n)),
235 Class::Barrier(why) => {
236 if let Some(why) = why.filter(|w| !w.contains("__psync")) {
238 self.report.barriers.push(why);
239 }
240 out.extend(self.schedule_region(std::mem::take(&mut region), &mentions));
241 out.push(stmt);
242 }
243 }
244 }
245 out.extend(self.schedule_region(region, &mentions));
246 out
247 }
248
249 fn schedule_region(&mut self, region: Vec<(usize, Node)>, mentions: &[Set]) -> Vec<Stmt> {
251 if region.iter().filter(|(_, n)| n.awaits).count() < 2 {
252 return region.into_iter().map(|(_, n)| n.stmt).collect();
253 }
254 let (positions, mut nodes): (Vec<usize>, Vec<Node>) = region.into_iter().unzip();
255 let baseline = self.options.baseline == Some(crate::Baseline::Resync);
256 if baseline {
257 crate::effects::per_environment(&mut nodes);
258 }
259 let strict = match self.options.owned_files {
262 true => crate::gates::widen_files(&nodes),
263 false => nodes.clone(),
264 };
265 let relaxed = (!baseline)
268 .then(|| {
269 crate::gates::relax(
270 &nodes,
271 &strict,
272 &self.scope.mutable,
273 &mut self.fresh,
274 &crate::gates::Compare {
275 krate: &self.options.krate,
276 owned_files: self.options.owned_files,
277 },
278 )
279 })
280 .flatten();
281 let (plan, gates, prelude) = match relaxed {
282 Some((plan, gates, prelude)) => (plan, gates, prelude),
283 None => (plan(&strict), Vec::new(), Vec::new()),
284 };
285 let mut report = plan.report.clone();
286 report.runtime_checks = gates.len();
287 self.report.regions.push(report);
288 if !plan.report.changed {
289 return nodes.into_iter().map(|n| n.stmt).collect();
290 }
291 let mut out = prelude;
292 out.extend(emit(
293 self.scope.sync,
294 &self.options.krate,
295 &self.scope.fresh,
296 nodes,
297 &plan,
298 &positions,
299 mentions,
300 &mut self.fresh,
301 &gates,
302 ));
303 out
304 }
305}
306
307fn is_control_flow(stmt: &Stmt) -> bool {
309 let expr = match stmt {
310 Stmt::Expr(e, _) => e,
311 Stmt::Local(Local {
312 init: Some(init), ..
313 }) => &init.expr,
314 _ => return false,
315 };
316 matches!(
317 expr,
318 Expr::If(_) | Expr::Match(_) | Expr::ForLoop(_) | Expr::While(_) | Expr::Loop(_)
319 )
320}
321
322fn bind_values(values: &mut std::collections::HashMap<String, Target>, stmt: &Stmt, mutable: &Set) {
327 let Stmt::Local(local) = stmt else {
328 return;
329 };
330 let mut bound = Vec::new();
331 crate::classify::pat_idents(&local.pat, &mut bound);
332 for (name, _) in &bound {
333 let name = name.to_string();
334 values.remove(&name);
335 values.retain(|_, t| t.names().is_none_or(|n| !n.contains(&name)));
336 }
337 let syn::Pat::Ident(p) = &local.pat else {
338 return;
339 };
340 let Some(init) = &local.init else {
341 return;
342 };
343 if p.mutability.is_some() || p.by_ref.is_some() || p.subpat.is_some() || init.diverge.is_some()
344 {
345 return;
346 }
347 let t = value_target(&init.expr);
348 if t.informative() && t.names().is_none_or(|n| n.is_disjoint(mutable)) {
349 values.insert(p.ident.to_string(), t);
350 }
351}
352
353fn awaited_value(stmt: &Stmt) -> bool {
356 let Stmt::Local(syn::Local {
357 init: Some(init), ..
358 }) = stmt
359 else {
360 return true;
361 };
362 let mut e = &*init.expr;
363 loop {
364 match e {
365 Expr::Await(_) => return true,
366 Expr::Try(t) => e = &t.expr,
367 Expr::Paren(p) => e = &p.expr,
368 Expr::MethodCall(m) => e = &m.receiver,
369 Expr::Field(f) => e = &f.base,
370 _ => return false,
371 }
372 }
373}