graphity_core/lib.rs
1//! Directed graphs and their analysis, for tools that see a program as graphs: components, orders and
2//! cycles, reachability, trees and dominators, and graphs derived from other graphs.
3//!
4//! This crate is the counterpart of the Java module `graphity-core`, package
5//! `com.kobayami.graphity`; the crates `graphity-controlflow`, `graphity-dot` and `graphity-mermaid`
6//! build on it and are released with it at the same version. A [`Graph`] has the nodes
7//! `0..node_count()` and holds nothing but its edges, in 4 bytes per node and per edge; names and
8//! other data on nodes and edges stay in arrays of the caller, indexed by node ID or edge index.
9//! [`GraphBuilder`] builds a graph from a model of the caller, and the algorithms take the graph and
10//! return immutable results. None of them recurses, so a deep graph does not overflow the call stack.
11//! Here, the packages of a small program and the packages each of them uses become a graph, which
12//! has a cycle:
13//!
14//! <!-- example: getting_started.rs#firstResult -->
15//! ```
16//! # use graphity_core::{GraphBuilder, graphs};
17//! // The packages are the nodes 0 to 7, and uses[p] lists the packages that package p
18//! // uses.
19//! let names = [
20//! "app", "cli", "ui", "service", "model", "storage", "json", "util",
21//! ];
22//! let uses: [&[u32]; 8] = [
23//! &[1, 2, 3],
24//! &[7],
25//! &[3, 4, 7],
26//! &[4, 5],
27//! &[5],
28//! &[4, 6, 7],
29//! &[7],
30//! &[],
31//! ];
32//!
33//! // Build the graph: an edge p -> q for every package q that p uses.
34//! let mut builder = GraphBuilder::new();
35//! builder.add_nodes(uses.len() as u32);
36//! for (pkg, used) in uses.iter().enumerate() {
37//! builder.add_out_edges(pkg as u32, used);
38//! }
39//! let dependencies = builder.build();
40//!
41//! // Find a cycle.
42//! let cycle = graphs::find_cycle(&dependencies);
43//! // cycle: [4, 5] - model and storage use each other
44//! # assert_eq!(cycle, [4, 5]);
45//! # assert_eq!([names[4], names[5]], ["model", "storage"]);
46//! ```
47//!
48//! # Graphs
49//!
50//! - [`Graph`] - a directed graph with the out-nodes of every node; [`BiAdjacentGraph`] - one that
51//! also holds the in-nodes, for the algorithms that follow edges against their direction. It gives
52//! the transposed graph as well.
53//! - [`GraphBuilder`] - builds a graph from edges in any order; [`Graph::of`] takes the arrays of its
54//! CSR (compressed sparse row) layout, which [`csr`] hands to algorithm code of your own.
55//! - [`Graph::write_to`] and [`Graph::read_from`] - store a graph in a stream and load it again.
56//! - [`SortedIntView`] - the sorted list of node IDs or edge indices that lookups such as
57//! [`Graph::out_nodes`] return; [`Edges`] - a list of edges, each with its source, target and edge
58//! index.
59//! - [`graphs::adjacency_list_of`], [`graphs::topology_hash`] and [`graphs::diff`] - a whole graph as
60//! text, a hash to keep, and the edges added and removed between two versions of a graph.
61//!
62//! # Components and connectivity
63//!
64//! - [`components::sccs_of`] - the SCCs (strongly connected components), as [`Sccs`].
65//! - [`components::wccs_of`] - the weakly connected components, which are the components of the graph
66//! read as undirected.
67//! - [`components::biconnectivity_of`] - the bridges, articulation points and biconnected
68//! components, as [`Biconnectivity`].
69//! - [`components::strong_connectivity_of`] - the strong bridges and strong articulation points, as
70//! [`StrongConnectivity`].
71//! - [`graphs::is_strongly_connected`] and [`graphs::is_weakly_connected`] - the same questions for
72//! the whole graph, answered without the components.
73//!
74//! # Orders, cycles and traversals
75//!
76//! - [`top_order`] - a topological order of a DAG (directed acyclic graph); [`TopOrderAndLevels`] -
77//! one with a level per node.
78//! - [`graphs::is_dag`] and [`graphs::find_cycle`] - whether a graph has a cycle, and one of its
79//! cycles.
80//! - [`EdgeTypes`] - the tree, back, forward and cross edges of a depth-first search; [`back_edges`] -
81//! the back edges alone.
82//! - [`DfsTraverser`], [`DfsEdgeTraverser`] and [`FrontierTraverser`] - depth-first and breadth-first
83//! searches of your own, with the hooks of [`DfsHooks`], [`DfsEdgeHooks`] and [`FrontierHooks`].
84//!
85//! # Reachability and distances
86//!
87//! - [`graphs::reachable_from`] and [`graphs::reachable_from_sources`] - the nodes reachable from one
88//! or several nodes;
89//! [`graphs::root_nodes`] - the nodes with in-degree 0, called root nodes.
90//! - [`BfsDistances`] - distances and shortest paths from one or several nodes.
91//! - [`graphs::transitive_closure`] and [`graphs::transitive_reduction`] - an edge for every path, and
92//! the fewest edges for the same paths.
93//!
94//! # Trees and dominators
95//!
96//! - [`Ancestry`] - parent, depth and lowest common ancestor in a forest; [`PreorderAncestry`] - the
97//! ancestor test in O(1) and the nodes of each subtree.
98//! - [`graphs::is_tree`], [`graphs::is_forest`] and [`graphs::is_path`] - shape checks, and their
99//! counterparts for the graph read as undirected, such as [`graphs::is_undirected_tree`].
100//! - [`Dominators`] - the dominators of a control-flow graph, and on its transposed graph the
101//! post-dominators; [`graphs::dominator_tree`] - the dominator tree as a graph.
102//!
103//! Loops, dominance frontiers, control dependence and the placement of phi-nodes are in the crate
104//! `graphity-controlflow`. The crate `graphity-mermaid` writes a graph as a Mermaid flowchart, and
105//! `graphity-dot` writes it as text in DOT (the language of Graphviz).
106//!
107//! # Derived graphs and the data on them
108//!
109//! - [`graphs::remapped`] with a [`NodeMapping`] - a subgraph or a graph with renumbered nodes;
110//! [`EdgeMapping`] carries data on the edges over to it.
111//! - [`NodePartition::condense`] - the condensed graph of a partition of the nodes into groups;
112//! [`EdgePartition`] - the edges behind each of its edges.
113//! - [`BiAdjacentGraph::transposed`] - the transposed graph, without copying;
114//! [`graphs::transposed_edge_mapping`] carries data on the edges over to it.
115//!
116//! # Rust and Java
117//!
118//! The names are Java's in snake case, and the numbers are `u32`. Where Java returns `-1` for "none",
119//! a single lookup returns `Option<u32>`, and an array of the caller uses [`NONE`]. An operation that
120//! checks a whole input returns a [`Result`] with a [`GraphError`]; a single argument out of its range
121//! panics, like an out-of-range slice index. The [`error`] module describes how both keep Java's
122//! distinction between `IndexOutOfBoundsException` and `IllegalArgumentException`. Every type is
123//! `Send` and `Sync`.
124
125mod ancestry;
126mod array_limits;
127pub mod back_edges;
128mod bfs_distances;
129mod biconnectivity;
130mod bits;
131mod builder;
132pub mod components;
133pub mod csr;
134mod csr_streams;
135mod dfs_edge_traverser;
136mod dfs_frames;
137mod dfs_preorder;
138mod dfs_traverser;
139mod dominators;
140mod edge_types;
141mod edges;
142pub mod error;
143mod frontier_traverser;
144mod graph;
145mod graph_diff;
146pub mod graphs;
147mod growth;
148mod mapping;
149mod parent_forest;
150mod partition;
151mod sccs;
152mod sorted_int_view;
153mod strong_connectivity;
154pub mod top_order;
155mod top_order_and_levels;
156mod union_find;
157
158pub use ancestry::{Ancestry, PreorderAncestry};
159pub use bfs_distances::BfsDistances;
160pub use biconnectivity::Biconnectivity;
161pub use builder::GraphBuilder;
162pub use dfs_edge_traverser::{DfsEdgeHooks, DfsEdgeTraverser, EdgeAction, TargetState};
163pub use dfs_traverser::{DfsControl, DfsHooks, DfsTraverser};
164pub use dominators::Dominators;
165pub use edge_types::{EdgeType, EdgeTypes};
166pub use edges::Edges;
167pub use error::{ErrorKind, GraphError};
168pub use frontier_traverser::{FrontierControl, FrontierHooks, FrontierTraverser};
169pub use graph::{BiAdjacentGraph, Graph};
170pub use graph_diff::GraphDiff;
171pub use mapping::{EdgeMapping, IndexMapping, NodeMapping};
172pub use partition::{EdgePartition, IndexPartition, NodePartition};
173pub use sccs::Sccs;
174pub use sorted_int_view::SortedIntView;
175pub use strong_connectivity::StrongConnectivity;
176pub use top_order_and_levels::TopOrderAndLevels;
177
178/// The value for "none" in the arrays this crate takes, such as the `group_of` of
179/// [`NodePartition::of`]: a node in no group, or a node that maps to no node. It has the same bits as
180/// Java's `-1` and is never a valid node ID or edge index.
181pub const NONE: u32 = u32::MAX;