1use crate::access::{Access, PURE_METHODS, Set, scan};
10use crate::effects::{self, Effect};
11use proc_macro2::{Delimiter, Ident, Span, TokenStream, TokenTree};
12use quote::ToTokens;
13use syn::{Attribute, Expr, Local, LocalInit, Pat, Stmt, spanned::Spanned, visit::Visit};
14
15pub(crate) struct Scope {
17 pub mutable: Set,
19 pub handles: Set,
21 pub fresh: std::collections::BTreeMap<String, (Ident, TokenStream)>,
25 pub effects: effects::Config,
27 pub sync: bool,
30}
31
32#[derive(Clone)]
34pub(crate) struct Node {
35 pub stmt: Stmt,
37 pub defs: Vec<(Ident, bool)>,
39 pub acc: Access,
41 pub awaits: bool,
43 pub blocks: bool,
45 pub effect: bool,
48 pub exits: bool,
50 pub effects: Vec<Effect>,
52 pub unclassified: Vec<String>,
54 pub speculate: bool,
56 pub panics: bool,
58 pub independent: bool,
61 pub label: String,
63 pub line: usize,
65 pub end_line: usize,
67}
68
69pub(crate) enum Class {
71 Node(Box<Node>),
72 Barrier(Option<String>),
74}
75
76const GUARD_AWAITS: &[&str] = &[
81 "lock",
82 "lock_owned",
83 "read",
84 "write",
85 "acquire",
86 "acquire_owned",
87 "acquire_many",
88 "begin",
89 "transaction",
90];
91const DELAY_AWAITS: &[&str] = &["sleep", "sleep_until", "tick", "yield_now", "delay_for"];
96pub(crate) const AWAITING_MACROS: &[&str] = &["select", "select_biased", "join", "try_join"];
103const CLOCK_CALLS: &[&str] = &["now", "elapsed", "duration_since"];
109fn reads_clock(tokens: TokenStream) -> bool {
113 let tokens: Vec<TokenTree> = tokens.into_iter().collect();
114 tokens.iter().enumerate().any(|(i, t)| match t {
115 TokenTree::Ident(id) => {
116 CLOCK_CALLS.contains(&id.to_string().as_str())
117 && matches!(tokens.get(i + 1), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
118 }
119 TokenTree::Group(g) => {
121 let deferred = tokens[..i].iter().rev().take(2).any(|p| {
122 matches!(p, TokenTree::Punct(c) if c.as_char() == '|')
123 || matches!(p, TokenTree::Ident(k) if k == "async" || k == "move")
124 });
125 !deferred && reads_clock(g.stream())
126 }
127 _ => false,
128 })
129}
130
131const NET_PATHS: &[&str] = &["ureq", "TcpStream", "UdpSocket"];
138const NET_WAITS: &[&str] = &[
141 "connect",
142 "call",
143 "send",
144 "send_to",
145 "recv",
146 "recv_from",
147 "read_to_end",
148 "read_to_string",
149 "read_exact",
150];
151const PROCESS_WAITS: &[&str] = &["output", "status", "wait", "wait_with_output"];
154const GUARD_METHODS: &[&str] = &["lock", "try_lock", "borrow", "borrow_mut", "read", "write"];
160fn any_token(tokens: TokenStream, f: &dyn Fn(&[TokenTree], usize) -> bool) -> bool {
166 let tokens: Vec<TokenTree> = tokens.into_iter().collect();
167 tokens.iter().enumerate().any(|(i, t)| match t {
168 TokenTree::Group(g) => {
169 let deferred = tokens[..i].iter().rev().take(2).any(|p| {
170 matches!(p, TokenTree::Punct(c) if c.as_char() == '|')
171 || matches!(p, TokenTree::Ident(k) if k == "async" || k == "move")
172 });
173 let macro_args =
174 i > 0 && matches!(&tokens[i - 1], TokenTree::Punct(c) if c.as_char() == '!');
175 !deferred && !macro_args && any_token(g.stream(), f)
176 }
177 _ => f(&tokens, i),
178 })
179}
180
181fn blocks_on_world(tokens: TokenStream) -> bool {
184 let named = |set: &'static [&'static str]| {
185 move |ts: &[TokenTree], i: usize| match &ts[i] {
186 TokenTree::Ident(id) if set.contains(&id.to_string().as_str()) => true,
187 TokenTree::Ident(id) if id == "reqwest" && set == NET_PATHS => {
188 matches!(ts.get(i + 3), Some(TokenTree::Ident(b)) if b == "blocking")
189 }
190 _ => false,
191 }
192 };
193 let calls = |set: &'static [&'static str]| {
195 move |ts: &[TokenTree], i: usize| {
196 matches!(&ts[i], TokenTree::Ident(m) if set.contains(&m.to_string().as_str()))
197 && i > 0
198 && matches!(&ts[i - 1], TokenTree::Punct(p)
199 if p.as_char() == '.' || (p.as_char() == ':' && set == NET_WAITS))
200 && matches!(ts.get(i + 1), Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis)
201 }
202 };
203 let net = any_token(tokens.clone(), &named(NET_PATHS))
204 && any_token(tokens.clone(), &calls(NET_WAITS));
205 let process = any_token(
206 tokens.clone(),
207 &|ts, i| matches!(&ts[i], TokenTree::Ident(id) if id == "Command"),
208 ) && any_token(tokens, &calls(PROCESS_WAITS));
209 net || process
210}
211
212fn takes_guard(tokens: TokenStream) -> bool {
214 any_token(tokens, &|ts, i| {
215 matches!(
216 (&ts[i], ts.get(i + 1), i.checked_sub(1).map(|p| &ts[p])),
217 (TokenTree::Ident(m), Some(TokenTree::Group(g)), Some(TokenTree::Punct(dot)))
218 if dot.as_char() == '.'
219 && g.delimiter() == Delimiter::Parenthesis
220 && g.stream().is_empty()
221 && GUARD_METHODS.contains(&m.to_string().as_str())
222 )
223 })
224}
225
226const LOG_MACROS: &[&str] = &["trace", "debug", "info", "warn", "error", "log"];
229const PURE_MACROS: &[&str] = &["format", "vec", "concat", "stringify"];
234#[derive(Default)]
239pub(crate) struct Exits {
240 local_labels: Vec<String>,
242 loop_depth: usize,
244 pub awaits: bool,
245 pub exits: bool,
246 pub awaited: Vec<String>,
248 pub awaited_unscoped: Vec<String>,
251 block_depth: usize,
253 pub blocker: Option<String>,
255}
256
257impl Exits {
258 pub fn of(e: &Expr) -> Self {
259 let mut x = Exits::default();
260 x.visit_expr(e);
261 x
262 }
263 pub fn of_stmt(s: &Stmt) -> Self {
264 let mut x = Exits::default();
265 x.visit_stmt(s);
266 x
267 }
268 fn leaves(&self, label: Option<&syn::Lifetime>) -> bool {
269 match label {
270 Some(l) => {
271 let name = l.ident.to_string();
272 !name.starts_with("__psync") && !self.local_labels.contains(&name)
273 }
274 None => self.loop_depth == 0,
275 }
276 }
277 fn in_loop(&mut self, label: Option<&syn::Label>, f: impl FnOnce(&mut Self)) {
278 match label {
279 Some(l) => {
280 self.local_labels.push(l.name.ident.to_string());
281 self.loop_depth += 1;
282 f(self);
283 self.loop_depth -= 1;
284 self.local_labels.pop();
285 }
286 None => {
287 self.loop_depth += 1;
288 f(self);
289 self.loop_depth -= 1;
290 }
291 }
292 }
293}
294
295impl<'ast> Visit<'ast> for Exits {
296 fn visit_expr_closure(&mut self, _: &'ast syn::ExprClosure) {}
297 fn visit_expr_async(&mut self, _: &'ast syn::ExprAsync) {}
298 fn visit_item(&mut self, _: &'ast syn::Item) {}
299 fn visit_block(&mut self, b: &'ast syn::Block) {
300 self.block_depth += 1;
301 syn::visit::visit_block(self, b);
302 self.block_depth -= 1;
303 }
304 fn visit_expr_await(&mut self, e: &'ast syn::ExprAwait) {
305 self.awaits = true;
306 self.awaited.push(callee(&e.base));
307 if self.block_depth == 0 {
308 self.awaited_unscoped.push(callee(&e.base));
309 }
310 syn::visit::visit_expr_await(self, e);
311 }
312 fn visit_expr_try(&mut self, e: &'ast syn::ExprTry) {
313 self.exits = true;
314 syn::visit::visit_expr_try(self, e);
315 }
316 fn visit_expr_return(&mut self, e: &'ast syn::ExprReturn) {
317 self.exits = true;
318 syn::visit::visit_expr_return(self, e);
319 }
320 fn visit_expr_yield(&mut self, e: &'ast syn::ExprYield) {
321 self.blocker.get_or_insert_with(|| "`yield`".into());
322 syn::visit::visit_expr_yield(self, e);
323 }
324 fn visit_expr_break(&mut self, e: &'ast syn::ExprBreak) {
325 if self.leaves(e.label.as_ref()) {
326 if e.expr.is_some() {
327 self.blocker
328 .get_or_insert_with(|| "`break` with a value".into());
329 }
330 self.exits = true;
331 }
332 syn::visit::visit_expr_break(self, e);
333 }
334 fn visit_expr_continue(&mut self, e: &'ast syn::ExprContinue) {
335 if self.leaves(e.label.as_ref()) {
336 self.exits = true;
337 }
338 }
339 fn visit_expr_for_loop(&mut self, e: &'ast syn::ExprForLoop) {
340 self.visit_expr(&e.expr);
341 self.in_loop(e.label.as_ref(), |x| x.visit_block(&e.body));
342 }
343 fn visit_expr_while(&mut self, e: &'ast syn::ExprWhile) {
344 self.visit_expr(&e.cond);
345 self.in_loop(e.label.as_ref(), |x| x.visit_block(&e.body));
346 }
347 fn visit_expr_loop(&mut self, e: &'ast syn::ExprLoop) {
348 self.in_loop(e.label.as_ref(), |x| x.visit_block(&e.body));
349 }
350 fn visit_expr_block(&mut self, e: &'ast syn::ExprBlock) {
351 if let Some(l) = &e.label {
352 self.local_labels.push(l.name.ident.to_string());
353 self.visit_block(&e.block);
354 self.local_labels.pop();
355 } else {
356 self.visit_block(&e.block);
357 }
358 }
359 fn visit_macro(&mut self, m: &'ast syn::Macro) {
360 fn walk(ts: TokenStream, awaits: &mut bool, exits: &mut bool) {
362 for tt in ts {
363 match tt {
364 TokenTree::Group(g) => walk(g.stream(), awaits, exits),
365 TokenTree::Ident(i) if i == "await" => *awaits = true,
366 TokenTree::Ident(i) if i == "return" => *exits = true,
367 TokenTree::Punct(p) if p.as_char() == '?' => *exits = true,
368 _ => {}
369 }
370 }
371 }
372 let name = macro_name(m);
373 let (mut awaits, mut exits) = (false, false);
374 walk(m.tokens.clone(), &mut awaits, &mut exits);
375 self.awaits |= awaits;
376 if AWAITING_MACROS.contains(&name.as_str()) {
378 self.awaits = true;
379 self.blocker.get_or_insert_with(|| {
380 format!("`{name}!` awaits calls psync cannot see inside the macro")
381 });
382 }
383 let exits = exits && !LOG_MACROS.contains(&name.as_str());
385 if exits
386 || matches!(
387 name.as_str(),
388 "bail" | "ensure" | "try" | "return_err" | "fail"
389 )
390 {
391 self.blocker
392 .get_or_insert_with(|| format!("`{name}!` may return early"));
393 }
394 }
395}
396
397pub(crate) fn macro_name(m: &syn::Macro) -> String {
398 m.path
399 .segments
400 .last()
401 .map(|s| s.ident.to_string())
402 .unwrap_or_default()
403}
404
405fn callee(e: &Expr) -> String {
407 match e {
408 Expr::MethodCall(m) => m.method.to_string(),
409 Expr::Call(c) => match &*c.func {
410 Expr::Path(p) => {
411 let segs: Vec<String> = p
412 .path
413 .segments
414 .iter()
415 .map(|s| s.ident.to_string())
416 .collect();
417 segs[segs.len().saturating_sub(2)..].join("::")
418 }
419 _ => "call".into(),
420 },
421 Expr::Macro(m) => format!("{}!", macro_name(&m.mac)),
422 Expr::Paren(p) => callee(&p.expr),
423 Expr::Try(t) => callee(&t.expr),
424 other => other
425 .to_token_stream()
426 .to_string()
427 .chars()
428 .take(18)
429 .collect(),
430 }
431}
432
433pub(crate) fn is_pure(e: &Expr) -> bool {
435 match e {
436 Expr::Lit(_) | Expr::Path(_) | Expr::Closure(_) | Expr::Range(_) => true,
437 Expr::Field(f) => is_pure(&f.base),
438 Expr::Reference(r) => r.mutability.is_none() && is_pure(&r.expr),
439 Expr::Paren(p) => is_pure(&p.expr),
440 Expr::Group(g) => is_pure(&g.expr),
441 Expr::Unary(u) => is_pure(&u.expr),
442 Expr::Binary(b) => is_pure(&b.left) && is_pure(&b.right),
443 Expr::Cast(c) => is_pure(&c.expr),
444 Expr::Index(i) => is_pure(&i.expr) && is_pure(&i.index),
445 Expr::Tuple(t) => t.elems.iter().all(is_pure),
446 Expr::Array(a) => a.elems.iter().all(is_pure),
447 Expr::Struct(s) => {
448 s.fields.iter().all(|f| is_pure(&f.expr)) && s.rest.as_ref().is_none_or(|r| is_pure(r))
449 }
450 Expr::If(i) => {
452 is_pure(&i.cond)
453 && pure_block(&i.then_branch)
454 && i.else_branch.as_ref().is_some_and(|(_, e)| match &**e {
455 Expr::Block(b) => pure_block(&b.block),
456 e => is_pure(e),
457 })
458 }
459 Expr::Block(b) if b.label.is_none() => pure_block(&b.block),
460 Expr::MethodCall(m) => {
461 (PURE_METHODS.contains(&m.method.to_string().as_str())
463 || (m.method == "join" && m.args.len() == 1))
464 && is_pure(&m.receiver)
465 && m.args.iter().all(is_pure)
466 }
467 Expr::Call(c) => {
468 let Expr::Path(p) = &*c.func else {
470 return false;
471 };
472 let last = p
473 .path
474 .segments
475 .last()
476 .map(|s| s.ident.to_string())
477 .unwrap_or_default();
478 let ctor = matches!(
479 last.as_str(),
480 "new" | "from" | "default" | "with_capacity" | "Some" | "Ok" | "Err"
481 ) || (p.path.segments.len() == 1 && last.starts_with(char::is_uppercase));
482 ctor && c.args.iter().all(is_pure)
483 }
484 Expr::Macro(m) => {
485 let e = Exits::of(&Expr::Macro(m.clone()));
486 PURE_MACROS.contains(¯o_name(&m.mac).as_str()) && !e.awaits && e.blocker.is_none()
487 }
488 _ => false,
489 }
490}
491
492fn pure_block(b: &syn::Block) -> bool {
494 matches!(&b.stmts[..], [Stmt::Expr(e, None)] if is_pure(e))
495}
496
497pub(crate) fn is_place(e: &Expr) -> bool {
499 match e {
500 Expr::Path(_) => true,
501 Expr::Field(f) => is_place(&f.base),
502 Expr::Index(i) => is_place(&i.expr) && is_pure(&i.index),
503 Expr::Paren(p) => is_place(&p.expr),
504 Expr::Unary(u) => matches!(u.op, syn::UnOp::Deref(_)) && is_place(&u.expr),
505 _ => false,
506 }
507}
508
509pub(crate) fn pat_idents(pat: &Pat, out: &mut Vec<(Ident, bool)>) {
511 struct V<'a>(&'a mut Vec<(Ident, bool)>);
512 impl<'ast> Visit<'ast> for V<'_> {
513 fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
514 self.0.push((p.ident.clone(), p.mutability.is_some()));
515 syn::visit::visit_pat_ident(self, p);
516 }
517 fn visit_path(&mut self, _: &'ast syn::Path) {}
519 }
520 V(out).visit_pat(pat);
521}
522
523pub(crate) fn pat_has_ref(pat: &Pat) -> bool {
525 struct V(bool);
526 impl<'ast> Visit<'ast> for V {
527 fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
528 self.0 |= p.by_ref.is_some();
529 syn::visit::visit_pat_ident(self, p);
530 }
531 }
532 let mut v = V(false);
533 v.visit_pat(pat);
534 v.0
535}
536
537pub(crate) const HINTS: &[&str] = &["seq", "fresh", "independent", "speculate", "par"];
540pub(crate) fn expr_attrs(e: &Expr) -> &[Attribute] {
544 match e {
545 Expr::Try(t) => &t.attrs,
546 Expr::Await(a) => &a.attrs,
547 Expr::MethodCall(m) => &m.attrs,
548 Expr::Call(c) => &c.attrs,
549 Expr::If(i) => &i.attrs,
550 Expr::Match(m) => &m.attrs,
551 Expr::ForLoop(f) => &f.attrs,
552 Expr::While(w) => &w.attrs,
553 Expr::Assign(a) => &a.attrs,
554 Expr::Block(b) => &b.attrs,
555 _ => &[],
556 }
557}
558
559pub(crate) fn is_psync_attr(attr: &Attribute, name: &str) -> bool {
561 let segs: Vec<String> = attr
562 .path()
563 .segments
564 .iter()
565 .map(|s| s.ident.to_string())
566 .collect();
567 segs.last().is_some_and(|l| l == name)
568 && (segs.len() == 1 && name == "graph" || segs.first().is_some_and(|f| f == "psync"))
569}
570
571pub(crate) fn end_line_of(span: Span) -> usize {
573 #[cfg(feature = "cli")]
574 {
575 span.end().line
576 }
577 #[cfg(not(feature = "cli"))]
578 {
579 let _ = span;
580 0
581 }
582}
583
584pub(crate) fn line_of(span: Span) -> usize {
586 #[cfg(feature = "cli")]
587 {
588 span.start().line
589 }
590 #[cfg(not(feature = "cli"))]
591 {
592 let _ = span;
593 0
594 }
595}
596
597pub(crate) fn bindings_in(block: &syn::Block) -> Set {
599 struct V(Set);
600 impl<'ast> Visit<'ast> for V {
601 fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
602 self.0.insert(p.ident.to_string());
603 syn::visit::visit_pat_ident(self, p);
604 }
605 }
606 let mut v = V(Set::new());
607 v.visit_block(block);
608 v.0
609}
610
611pub(crate) fn inner_bindings(stmt: &Stmt) -> Set {
613 struct V(Set);
614 impl<'ast> Visit<'ast> for V {
615 fn visit_pat_ident(&mut self, p: &'ast syn::PatIdent) {
616 self.0.insert(p.ident.to_string());
617 syn::visit::visit_pat_ident(self, p);
618 }
619 }
620 let mut v = V(Set::new());
621 match stmt {
622 Stmt::Local(l) => {
623 if let Some(init) = &l.init {
624 v.visit_expr(&init.expr);
625 if let Some((_, d)) = &init.diverge {
626 v.visit_expr(d);
627 }
628 }
629 }
630 other => v.visit_stmt(other),
631 }
632 v.0
633}
634
635fn label_for(defs: &[(Ident, bool)], stmt: &Stmt, x: &Exits) -> String {
637 let rhs = match x.awaited.first() {
638 Some(c) if c.ends_with('!') => c.clone(),
639 Some(c) => format!("{c}()"),
640 None => match stmt {
641 Stmt::Macro(m) => format!("{}!", macro_name(&m.mac)),
642 Stmt::Local(Local {
644 init: Some(init), ..
645 }) => {
646 let text = init.expr.to_token_stream().to_string();
647 match text.char_indices().nth(23) {
648 Some((cut, _)) => format!("{}…", &text[..cut]),
649 None => text,
650 }
651 }
652 _ => stmt
653 .to_token_stream()
654 .to_string()
655 .chars()
656 .take(24)
657 .collect(),
658 },
659 };
660 let rhs = if x.exits { format!("{rhs}?") } else { rhs };
661 if defs.is_empty() {
662 rhs
663 } else {
664 let names: Vec<String> = defs.iter().map(|(i, _)| i.to_string()).collect();
665 format!("{} = {rhs}", names.join(", "))
666 }
667}
668
669pub(crate) fn classify(stmt: &Stmt, scope: &Scope, relaxed: bool) -> Class {
674 let seq = |attrs: &[Attribute]| attrs.iter().any(|a| is_psync_attr(a, "seq"));
675 let x = Exits::of_stmt(stmt);
676 let describe = |why: &str| {
677 x.awaits.then(|| {
678 let text: String = stmt
679 .to_token_stream()
680 .to_string()
681 .chars()
682 .take(60)
683 .collect();
684 format!("line {}: `{text}`: {why}", line_of(stmt.span()))
685 })
686 };
687 let (attrs, pat, value, shaped): (&[Attribute], Option<&Pat>, Option<&Expr>, bool) = match stmt
690 {
691 Stmt::Local(Local {
692 attrs,
693 pat,
694 init: Some(LocalInit { expr, .. }),
695 ..
696 }) => (attrs, Some(pat), Some(expr), true),
697 Stmt::Local(_) => return Class::Barrier(None),
698 Stmt::Expr(e, _) => {
701 let awaited = match e {
702 Expr::Await(_) => true,
703 Expr::Try(t) => matches!(&*t.expr, Expr::Await(_)),
704 _ => false,
705 };
706 (expr_attrs(e), None, Some(e), awaited)
707 }
708 Stmt::Macro(m) => (
709 &m.attrs,
710 None,
711 None,
712 LOG_MACROS.contains(¯o_name(&m.mac).as_str()),
713 ),
714 Stmt::Item(_) => return Class::Barrier(None),
715 };
716 if seq(attrs) {
717 return Class::Barrier(describe("marked #[psync::seq]"));
718 }
719 if attrs.iter().any(|a| is_psync_attr(a, "fresh")) {
721 return Class::Barrier(None);
722 }
723 if let Some(why) = &x.blocker {
724 return Class::Barrier(describe(why));
725 }
726 if reads_clock(stmt.to_token_stream()) {
727 let text: String = stmt
730 .to_token_stream()
731 .to_string()
732 .chars()
733 .take(60)
734 .collect();
735 return Class::Barrier(Some(format!(
736 "line {}: `{text}`: reads the clock, whose position is meaningful",
737 line_of(stmt.span())
738 )));
739 }
740 if pat.is_some_and(pat_has_ref) {
741 return Class::Barrier(describe("`ref` binding"));
742 }
743 let delay = x
744 .awaited
745 .iter()
746 .find(|m| DELAY_AWAITS.contains(&m.as_str()));
747 let guard = x
748 .awaited_unscoped
749 .iter()
750 .find(|m| GUARD_AWAITS.contains(&m.as_str()));
751 if let Some(m) = delay.or(guard) {
752 return Class::Barrier(describe(&format!(
753 "awaits `{m}`, whose position is meaningful"
754 )));
755 }
756 let blocks = scope.sync
759 && (attrs.iter().any(|a| is_psync_attr(a, "par"))
760 || blocks_on_world(stmt.to_token_stream()));
761 if scope.sync
762 && let Stmt::Local(l) = stmt
763 && l.init
764 .as_ref()
765 .is_some_and(|i| takes_guard(i.expr.to_token_stream()))
766 {
767 return Class::Barrier(None);
768 }
769 let awaits = x.awaits || blocks;
770 let shaped = shaped || blocks;
771 let pure_value = value.is_some_and(is_pure) || matches!(stmt, Stmt::Macro(_));
772 let mut effect = !shaped || (!awaits && !relaxed && !pure_value);
773 let mut defs = Vec::new();
774 if let Some(p) = pat {
775 pat_idents(p, &mut defs);
776 }
777 let mut acc = Access::default();
778 let tokens = match (stmt, value) {
779 (Stmt::Local(l), _) => {
780 let mut tokens = TokenStream::new();
781 if let Some(init) = &l.init {
782 tokens.extend(init.expr.to_token_stream());
783 if let Some((_, diverge)) = &init.diverge {
784 tokens.extend(diverge.to_token_stream());
785 }
786 }
787 tokens
788 }
789 (Stmt::Macro(m), _) => m.mac.tokens.clone(),
790 (_, Some(v)) => v.to_token_stream(),
791 _ => TokenStream::new(),
792 };
793 scan(tokens, &scope.mutable, &scope.handles, &mut acc);
794 let inner = inner_bindings(stmt);
796 acc.wpaths
797 .retain(|p| !inner.contains(crate::access::root(p)));
798 acc.writes.retain(|w| !inner.contains(w));
799 acc.wpaths
801 .retain(|p| !scope.fresh.contains_key(crate::access::root(p)));
802 acc.rpaths
803 .retain(|p| !scope.fresh.contains_key(crate::access::root(p)));
804 if relaxed && !shaped {
805 if !acc.wpaths.is_empty() || matches!(stmt, Stmt::Macro(_)) {
808 return Class::Barrier(None);
809 }
810 effect = false;
811 }
812 let mut found = effects::of_stmt_in(stmt, &scope.effects, scope.sync);
813 if blocks && found.effects.is_empty() {
816 let mut v = value;
817 while let Some(e) = v {
818 v = match e {
819 Expr::Try(t) => Some(&*t.expr),
820 Expr::MethodCall(m)
821 if matches!(m.method.to_string().as_str(), "unwrap" | "expect") =>
822 {
823 Some(&*m.receiver)
824 }
825 _ => break,
826 };
827 }
828 let op = v.map_or_else(|| "statement".to_string(), callee);
829 if scope.effects.unclassified_writes() {
830 found.effects.push(effects::Effect {
831 domain: effects::Domain::Unknown,
832 kind: effects::Kind::Write,
833 target: effects::Target::Any,
834 op: op.clone(),
835 ordered: true,
836 source: None,
837 });
838 }
839 found.unclassified.push(op);
840 }
841 for e in &mut found.effects {
845 if let effects::Domain::Service(Some(r)) = &mut e.domain
846 && inner.contains(crate::access::root(r))
847 {
848 use std::hash::{Hash, Hasher};
849 let mut h = std::collections::hash_map::DefaultHasher::new();
850 stmt.to_token_stream().to_string().hash(&mut h);
851 *r = format!("{r}@{:x}", h.finish() & 0xffff_ffff);
852 }
853 }
854 let speculate = scope.effects.speculate || attrs.iter().any(|a| is_psync_attr(a, "speculate"));
856 Class::Node(Box::new(Node {
857 effects: found.effects,
858 unclassified: found.unclassified,
859 panics: found.panics,
860 speculate,
861 independent: scope.effects.independent()
862 || attrs.iter().any(|a| is_psync_attr(a, "independent")),
863 stmt: stmt.clone(),
865 label: label_for(&defs, stmt, &x),
866 defs,
867 acc,
868 awaits,
869 blocks: blocks && !x.awaits,
870 effect,
871 exits: x.exits,
872 line: line_of(stmt.span()),
873 end_line: end_line_of(stmt.span()),
874 }))
875}