Something went wrong. Try again.
Rust compile+runtime deadlock prevention
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297//! Proc-macro support for `lock-ordering`.//!//! Provides the [`define_lock_levels!`] macro which generates marker structs and//! the full transitive [`LockAfter`] impl graph from a concise DAG declaration.//!//! [`LockAfter`]: lock_ordering::relation::LockAfter
use std::collections::{HashMap, HashSet, VecDeque};
use proc_macro::TokenStream;use proc_macro2::Span;use quote::quote;use syn::{ parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, Ident, Token,};
// ── Input parsing ────────────────────────────────────────────────────────────
struct Edge { from: Ident, to: Ident, /// `true` for `=>` (ordering — target requires parent, no `LockAfter<Unlocked>`). /// `false` for `->` (leveling — target is also a root). requires: bool,}
impl Parse for Edge { fn parse(input: ParseStream) -> syn::Result<Self> { let from: Ident = input.parse()?; // Accept either `->` (leveling) or `=>` (ordering/requires). let requires = if input.peek(Token![=>]) { input.parse::<Token![=>]>()?; true } else { input.parse::<Token![->]>()?; false }; let to: Ident = input.parse()?; Ok(Edge { from, to, requires }) }}
struct LockLevelInput { edges: Vec<Edge>,}
impl Parse for LockLevelInput { fn parse(input: ParseStream) -> syn::Result<Self> { let edges = Punctuated::<Edge, Token![,]>::parse_terminated(input)?; Ok(LockLevelInput { edges: edges.into_iter().collect(), }) }}
// ── Cycle detection ──────────────────────────────────────────────────────────
/// DFS-based cycle finder. Returns a vec of node indices forming the cycle,/// with the last element equal to the first (closed loop).fn find_cycle(adj: &[Vec<usize>], n: usize) -> Vec<usize> { // 0 = unvisited, 1 = on stack, 2 = done let mut color = vec![0u8; n]; let mut result = Vec::new();
for start in 0..n { if color[start] == 0 && dfs_find_cycle(start, adj, &mut color, &mut result) { return result; } }
result}
fn dfs_find_cycle( node: usize, adj: &[Vec<usize>], color: &mut Vec<u8>, path: &mut Vec<usize>,) -> bool { color[node] = 1; path.push(node);
for &next in &adj[node] { if color[next] == 1 { // Found back-edge to `next` — close the cycle let start = path.iter().position(|&x| x == next).unwrap(); let mut cycle = path[start..].to_vec(); cycle.push(next); *path = cycle; return true; } if color[next] == 0 && dfs_find_cycle(next, adj, color, path) { return true; } }
color[node] = 2; path.pop(); false}
// ── Macro implementation ─────────────────────────────────────────────────────
/// Declares a set of lock levels and their partial acquisition order.////// Two edge types are supported:////// - `A -> B` (**leveling**): while holding `A`, you may acquire `B`. Both `A`/// and `B` can be the first lock acquired./// - `A => B` (**ordering**): while holding `A`, you may acquire `B`. However,/// `B` *cannot* be the first lock acquired — it requires a parent lock.////// The macro generates:////// - A ZST marker struct for each declared level./// - [`LockAfter`] impls for all edges in the **transitive closure** of the/// declared DAG, so `A -> B -> C` automatically implies `A -> C`./// - [`LockAfter<Unlocked>`] for levels that are **not** the target of any `=>`/// edge, allowing them to be the first lock acquired.////// A cycle in the declared ordering is a compile-time error.////// # Example////// ```ignore/// use lock_ordering::define_lock_levels;////// define_lock_levels! {/// LockA -> LockB, // leveling: both are roots/// LockB => LockC, // ordering: C requires B/// }/// ```////// [`LockAfter`]: lock_ordering::relation::LockAfter/// [`LockAfter<Unlocked>`]: lock_ordering::relation::LockAfter#[proc_macro]pub fn define_lock_levels(input: TokenStream) -> TokenStream { let LockLevelInput { edges } = parse_macro_input!(input as LockLevelInput);
// ── Collect nodes in declaration order ─────────────────────────────────── let mut nodes: Vec<String> = Vec::new(); let mut node_set: HashSet<String> = HashSet::new();
for edge in &edges { for name in [edge.from.to_string(), edge.to.to_string()] { if node_set.insert(name.clone()) { nodes.push(name); } } }
if nodes.is_empty() { return TokenStream::new(); }
let n = nodes.len(); let node_index: HashMap<String, usize> = nodes.iter().enumerate().map(|(i, n)| (n.clone(), i)).collect();
// ── Build adjacency list ───────────────────────────────────────────────── let mut adj: Vec<Vec<usize>> = vec![vec![]; n]; let mut in_degree: Vec<usize> = vec![0; n];
for edge in &edges { let from = node_index[&edge.from.to_string()]; let to = node_index[&edge.to.to_string()];
if from == to { let msg = format!( "self-loop in lock ordering: {} -> {}", edge.from, edge.to ); return syn::Error::new(edge.from.span(), msg) .to_compile_error() .into(); }
// Avoid duplicate edges (doesn't affect correctness, keeps output tidy) if !adj[from].contains(&to) { adj[from].push(to); in_degree[to] += 1; } }
// ── Kahn's algorithm — cycle detection ─────────────────────────────────── let mut remaining = in_degree.clone(); let mut queue: VecDeque<usize> = (0..n).filter(|&i| remaining[i] == 0).collect(); let mut processed = 0;
while let Some(node) = queue.pop_front() { processed += 1; for &succ in &adj[node] { remaining[succ] -= 1; if remaining[succ] == 0 { queue.push_back(succ); } } }
if processed < n { let cycle = find_cycle(&adj, n); let cycle_str = cycle .iter() .map(|&i| nodes[i].as_str()) .collect::<Vec<_>>() .join(" -> "); let msg = format!("cycle detected in lock ordering: {}", cycle_str); let span = edges .iter() .find(|e| e.from == nodes[cycle[0]]) .map(|e| e.from.span()) .unwrap_or_else(Span::call_site); return syn::Error::new(span, msg).to_compile_error().into(); }
// ── Transitive closure (Floyd-Warshall) ────────────────────────────────── let mut reachable = vec![vec![false; n]; n]; for from in 0..n { for &to in &adj[from] { reachable[from][to] = true; } } for k in 0..n { for i in 0..n { if reachable[i][k] { let reachable_k = reachable[k].clone(); for (j, &reaches_j) in reachable_k.iter().enumerate() { if reaches_j { reachable[i][j] = true; } } } } }
// ── Code generation ────────────────────────────────────────────────────── let idents: Vec<Ident> = nodes .iter() .map(|name| Ident::new(name, Span::call_site())) .collect();
// Marker structs — no LockLevel impl; user implements that manually to choose // MutualExclusion vs ReadWrite and to associate a concrete Mutex type. let structs = idents.iter().map(|id| { quote! { #[derive(Debug, Clone, Copy)] pub struct #id; } });
// LockAfter impls for all edges in the transitive closure let mut lock_after_impls = Vec::new(); for from in 0..n { for to in 0..n { if reachable[from][to] { let from_id = &idents[from]; let to_id = &idents[to]; // "to can be acquired after from" → impl LockAfter<from> for to lock_after_impls.push(quote! { impl ::lock_ordering::relation::LockAfter<#from_id> for #to_id {} }); } } }
// Levels that are targets of `=>` edges require a parent — they do NOT get // `LockAfter<Unlocked>` and cannot be the first lock acquired. let mut requires_parent: HashSet<String> = HashSet::new(); for edge in &edges { if edge.requires { requires_parent.insert(edge.to.to_string()); } }
// Only root levels (not targets of `=>`) get LockAfter<Unlocked>. let unlocked_impls = idents.iter() .enumerate() .filter(|(i, _)| !requires_parent.contains(&nodes[*i])) .map(|(_, id)| { quote! { impl ::lock_ordering::relation::LockAfter< ::lock_ordering::Unlocked > for #id {} } });
quote! { #(#structs)* #(#lock_after_impls)* #(#unlocked_impls)* } .into()}