]> git.proxmox.com Git - rustc.git/blame - src/librustc_data_structures/graph/mod.rs
New upstream version 1.47.0+dfsg1
[rustc.git] / src / librustc_data_structures / graph / mod.rs
CommitLineData
e74abb32 1use rustc_index::vec::Idx;
1a4d82fc 2
8faf50e0
XL
3pub mod dominators;
4pub mod implementation;
5pub mod iterate;
6mod reference;
7pub mod scc;
dc9dc135 8pub mod vec_graph;
d9579d0f
AL
9
10#[cfg(test)]
416331ca 11mod tests;
1a4d82fc 12
8faf50e0
XL
13pub trait DirectedGraph {
14 type Node: Idx;
1a4d82fc
JJ
15}
16
8faf50e0
XL
17pub trait WithNumNodes: DirectedGraph {
18 fn num_nodes(&self) -> usize;
1a4d82fc
JJ
19}
20
dc9dc135
XL
21pub trait WithNumEdges: DirectedGraph {
22 fn num_edges(&self) -> usize;
23}
24
8faf50e0 25pub trait WithSuccessors: DirectedGraph
0531ce1d 26where
8faf50e0 27 Self: for<'graph> GraphSuccessors<'graph, Item = <Self as DirectedGraph>::Node>,
d9579d0f 28{
dfeec247 29 fn successors(&self, node: Self::Node) -> <Self as GraphSuccessors<'_>>::Iter;
dc9dc135
XL
30
31 fn depth_first_search(&self, from: Self::Node) -> iterate::DepthFirstSearch<'_, Self>
32 where
33 Self: WithNumNodes,
34 {
35 iterate::DepthFirstSearch::new(self, from)
36 }
d9579d0f
AL
37}
38
416331ca 39#[allow(unused_lifetimes)]
8faf50e0
XL
40pub trait GraphSuccessors<'graph> {
41 type Item;
42 type Iter: Iterator<Item = Self::Item>;
d9579d0f
AL
43}
44
8faf50e0 45pub trait WithPredecessors: DirectedGraph
0531ce1d 46where
8faf50e0 47 Self: for<'graph> GraphPredecessors<'graph, Item = <Self as DirectedGraph>::Node>,
476ff2be 48{
dfeec247 49 fn predecessors(&self, node: Self::Node) -> <Self as GraphPredecessors<'_>>::Iter;
1a4d82fc
JJ
50}
51
416331ca 52#[allow(unused_lifetimes)]
8faf50e0
XL
53pub trait GraphPredecessors<'graph> {
54 type Item;
55 type Iter: Iterator<Item = Self::Item>;
5bcae85e
SL
56}
57
8faf50e0
XL
58pub trait WithStartNode: DirectedGraph {
59 fn start_node(&self) -> Self::Node;
1a4d82fc
JJ
60}
61
8faf50e0
XL
62pub trait ControlFlowGraph:
63 DirectedGraph + WithStartNode + WithPredecessors + WithStartNode + WithSuccessors + WithNumNodes
64{
65 // convenient trait
66}
9cc50fc6 67
dfeec247 68impl<T> ControlFlowGraph for T where
8faf50e0
XL
69 T: DirectedGraph
70 + WithStartNode
71 + WithPredecessors
72 + WithStartNode
73 + WithSuccessors
dfeec247 74 + WithNumNodes
8faf50e0 75{
1a4d82fc 76}
e74abb32
XL
77
78/// Returns `true` if the graph has a cycle that is reachable from the start node.
79pub fn is_cyclic<G>(graph: &G) -> bool
80where
81 G: ?Sized + DirectedGraph + WithStartNode + WithSuccessors + WithNumNodes,
82{
83 iterate::TriColorDepthFirstSearch::new(graph)
84 .run_from_start(&mut iterate::CycleDetector)
85 .is_some()
86}