Skip to main content

graphity_all/
lib.rs

1//! Graphity is a graph library which keeps graphs in a compact, immutable form and provides
2//! algorithms on top of it, such as strongly and weakly connected components, bridges and
3//! articulation points, topological order and levels, cycle detection and edge classification,
4//! breadth-first distances and reachability, lowest common ancestors, dominators, loop nesting and
5//! condensed graphs.
6//!
7//! This is its Rust implementation, which follows the [Java
8//! library](https://github.com/kaufco/graphity) of the same version type by type and function by
9//! function.
10//!
11//! Every algorithm returns a typed, immutable result with follow-up queries, and runs without
12//! recursion, so deep graphs do not overflow the call stack. Data on nodes and edges stays in your
13//! own arrays, indexed by node ID or edge index, and every transformation tells you how to carry
14//! them along. The graph itself stores only structure: 4 bytes per node and per edge, in a
15//! compressed sparse row (CSR) layout, which is where speed and footprint come
16//! from.
17//!
18//! # Where to start
19//!
20//! The nodes of a [`Graph`] are the `u32` IDs `0..node_count()`, and its edges are numbered by edge
21//! index `0..edge_count()`, ordered by source and then by target. [`GraphBuilder`] builds a graph
22//! from edges in any order. The algorithms are not methods of the graph but functions and types of
23//! their own: `of` on a type named after the algorithm, such as [`Dominators::of`]; the functions
24//! of the modules [`components`] for the components, [`top_order`] and [`back_edges`]; and those of
25//! [`graphs`] for the rest, such as [`graphs::find_cycle`].
26//!
27//! A [`Graph`] holds the out-nodes of every node. [`BiAdjacentGraph::of`] adds the in-nodes. The
28//! algorithms that need them, such as [`Dominators`] and [`components::biconnectivity_of`], take a
29//! [`BiAdjacentGraph`]: build it once and pass it to all of them.
30//!
31//! The following example builds a graph of the dependencies between the packages of a small Rust
32//! program. These dependencies contain a cycle:
33//!
34//! <!-- example: getting_started.rs#firstResult -->
35//! ```
36//! # use graphity_all::{GraphBuilder, graphs};
37//! // The packages are the nodes 0 to 7, and uses[p] lists the packages that package p
38//! // uses.
39//! let names = [
40//!     "app", "cli", "ui", "service", "model", "storage", "json", "util",
41//! ];
42//! let uses: [&[u32]; 8] = [
43//!     &[1, 2, 3],
44//!     &[7],
45//!     &[3, 4, 7],
46//!     &[4, 5],
47//!     &[5],
48//!     &[4, 6, 7],
49//!     &[7],
50//!     &[],
51//! ];
52//!
53//! // Build the graph: an edge p -> q for every package q that p uses.
54//! let mut builder = GraphBuilder::new();
55//! builder.add_nodes(uses.len() as u32);
56//! for (pkg, used) in uses.iter().enumerate() {
57//!     builder.add_out_edges(pkg as u32, used);
58//! }
59//! let dependencies = builder.build();
60//!
61//! // Find a cycle.
62//! let cycle = graphs::find_cycle(&dependencies);
63//! // cycle: [4, 5] - model and storage use each other
64//! # assert_eq!(cycle, [4, 5]);
65//! # assert_eq!([names[4], names[5]], ["model", "storage"]);
66//! ```
67//!
68//! # Where to find what
69//!
70//! | Question | Entry points |
71//! |---|---|
72//! | How do I build a graph? | [`GraphBuilder`] from edges in any order, or [`Graph::of`] from the two arrays of a CSR layout. |
73//! | Which parts belong together? | [`components`]: strongly and weakly connected components, and the connected components of the graph read as undirected; bridges, articulation points and biconnected components; strong bridges and strong articulation points. |
74//! | In which order, and where are the cycles? | A topological order ([`top_order`]), and one with a level per node ([`TopOrderAndLevels`]); whether a graph has a cycle, and one of its cycles ([`graphs::is_dag`], [`graphs::find_cycle`]); the tree, back, forward and cross edges of a depth-first search ([`EdgeTypes`], [`back_edges`]). |
75//! | What is reachable, and how far? | The nodes reachable from one or several nodes ([`graphs::reachable_from`], [`graphs::reachable_from_sources`]); distances and shortest paths by breadth-first search ([`BfsDistances`]); transitive closure and, for a DAG (directed acyclic graph), transitive reduction ([`graphs::transitive_closure`], [`graphs::transitive_reduction`]). |
76//! | Who is the ancestor of whom in a tree? | Parent, depth and LCA (lowest common ancestor) in a forest ([`Ancestry`]); the ancestor test in O(1) and the nodes of each subtree ([`PreorderAncestry`]); shape checks such as [`graphs::is_tree`], [`graphs::is_path`] and [`graphs::is_bipartite`]. |
77//! | Which node dominates which? | Dominators from one or several entries, and post-dominators on the transposed graph ([`Dominators`]); the dominator tree ([`graphs::dominator_tree`]). |
78//! | Where are the loops, where do phi-nodes go, what controls what? (`graphity-controlflow`) | The loop nesting forest, irreducible loops included ([`controlflow::Loops`]); the blocks where SSA (static single assignment) form places phi-nodes ([`controlflow::IteratedDominanceFrontier`]); dominance frontiers and control dependence ([`controlflow::control_flow`]). |
79//! | How do I condense, filter or renumber a graph? | The condensed graph of a partition of your choosing ([`NodePartition::condense`]); subgraphs and renumbered graphs ([`graphs::remapped`] with a [`NodeMapping`]); the transposed graph, without copying ([`BiAdjacentGraph::transposed`]). |
80//! | How does my data follow a transformation? | [`NodeMapping`] for data on nodes; [`graphs::edge_mapping`], [`graphs::transposed_edge_mapping`] and [`graphs::edge_partition`] for data on edges. |
81//! | How do I store, load and compare graphs? | [`Graph::write_to`] and [`Graph::read_from`], as the two arrays of the CSR layout; a 64-bit hash of the nodes and edges ([`graphs::topology_hash`]); the edges added and removed between two versions of a graph ([`graphs::diff`]). |
82//! | How do I look at a graph? (`graphity-dot`, `graphity-mermaid`) | [`dot::DotWriter`] and [`mermaid::MermaidWriter`], with labels, attributes, shapes and clusters from your own arrays; [`graphs::adjacency_list_of`] for a whole graph as text. |
83//! | How do I write a search of my own? | The base types of depth-first and breadth-first searches, without recursion ([`DfsTraverser`], [`DfsEdgeTraverser`], [`FrontierTraverser`]); [`csr`] hands the arrays of a graph to loops of your own. |
84//!
85//! The documentation of each crate, listed below, groups its entry points by topic, and the
86//! documentation of each type names the algorithm it uses.
87//!
88//! # Contracts
89//!
90//! Every function states its contract: what it returns, and when it panics or returns an error,
91//! whether a result is a view or a copy, in which order the results come where that matters, and
92//! its cost in time and memory. Three rules hold across the whole API:
93//!
94//! - Where there is no result, a function returns `None`; an array of the caller marks an entry for
95//!   none with [`NONE`].
96//! - Graphs, mappings, partitions and the results of the algorithms are immutable and safe to share
97//!   between threads. The builder and the traversers are mutable, and a change needs a `&mut`
98//!   borrow; the writers hold arbitrary closures and are neither `Send` nor `Sync`.
99//! - A node ID, an edge index or any other ID or position outside its range panics with an
100//!   `index out of bounds` message, or is an [`ErrorKind::IndexOutOfBounds`] error where a whole
101//!   input is checked; any other invalid argument panics with an `invalid argument` message, or is
102//!   an [`ErrorKind::InvalidArgument`] error. The module [`error`] describes which operations return
103//!   errors.
104//!
105//! # Further references
106//!
107//! - **Guide:** [kaufco.github.io/graphity-doc](https://kaufco.github.io/graphity-doc/?lang=rust) - one page
108//!   per problem, from building a graph to control-flow analysis: the problem, the graph before and
109//!   after, and tested code, with an index by API and a glossary.
110//! - **README:** [kaufco/graphity-rust](https://github.com/kaufco/graphity-rust#readme) - how to
111//!   add Graphity to a project, and a first complete program.
112//! - **Repository:** [kaufco/graphity-rust](https://github.com/kaufco/graphity-rust) - the source
113//!   code and the changelog. It follows [Graphity for Java](https://github.com/kaufco/graphity),
114//!   where development happens.
115//!
116//! # Crates
117//!
118//! This crate is all of Graphity in one dependency. It has no code of its own: it has the items of
119//! `graphity-core` at its root and the other crates at [`controlflow`], [`dot`] and [`mermaid`].
120//!
121//! | Crate | Path here | What it adds |
122//! |---|---|---|
123//! | [`graphity-core`](graphity_core) | `graphity_all` | The graph, the builder, and every algorithm that applies to any directed graph, dominators included |
124//! | [`graphity-controlflow`](controlflow) | [`graphity_all::controlflow`](controlflow) | The analyses of control flow: loops, dominance frontiers, control dependence and the placement of phi-nodes |
125//! | [`graphity-dot`](dot) | [`graphity_all::dot`](dot) | A writer for DOT (the language of Graphviz) |
126//! | [`graphity-mermaid`](mermaid) | [`graphity_all::mermaid`](mermaid) | A writer for Mermaid flowcharts, which render in Markdown |
127//! | `graphity-all` | - | All of the above |
128
129#[doc(no_inline)]
130pub use graphity_core::*;
131
132#[doc(no_inline)]
133pub use graphity_controlflow as controlflow;
134
135#[doc(no_inline)]
136pub use graphity_dot as dot;
137
138#[doc(no_inline)]
139pub use graphity_mermaid as mermaid;