//! 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`). /// `false` for `->` (leveling — target is also a root). requires: bool, } impl Parse for Edge { fn parse(input: ParseStream) -> syn::Result { let from: Ident = input.parse()?; // Accept either `->` (leveling) or `=>` (ordering/requires). let requires = if input.peek(Token![=>]) { input.parse::]>()?; true } else { input.parse::]>()?; false }; let to: Ident = input.parse()?; Ok(Edge { from, to, requires }) } } struct LockLevelInput { edges: Vec, } impl Parse for LockLevelInput { fn parse(input: ParseStream) -> syn::Result { let edges = Punctuated::::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], n: usize) -> Vec { // 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], color: &mut Vec, path: &mut Vec, ) -> 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`] 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`]: 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 = Vec::new(); let mut node_set: HashSet = 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 = nodes.iter().enumerate().map(|(i, n)| (n.clone(), i)).collect(); // ── Build adjacency list ───────────────────────────────────────────────── let mut adj: Vec> = vec![vec![]; n]; let mut in_degree: Vec = 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 = (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::>() .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 = 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 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` and cannot be the first lock acquired. let mut requires_parent: HashSet = HashSet::new(); for edge in &edges { if edge.requires { requires_parent.insert(edge.to.to_string()); } } // Only root levels (not targets of `=>`) get LockAfter. 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() }