Scripting with uh graph and uh parse¶
uh graph builds the static call graph (and optionally the type graph) for a directory. It writes text, JSON or a compact binary archive to stdout. uh parse prints what the extractor finds in one file. Both use the same tree-sitter extractors as uh review. No compiler, language server or build step runs.
Use these commands to feed graphs into your tools, check resolution coverage in CI, or debug what uh sees in a file. Full flag list: CLI reference: uh graph.
uh graph . # text summary of the call graph
uh graph . --json > graph.json # compact JSON
uh parse src/main.rs # what was extracted from one file
What the graph contains¶
The call graph is condensed and layered:
- Each workspace callable is a node. Mutually recursive callables merge into one
recursive_groupnode (a strongly connected component), which keeps the graph acyclic. - Bodyless method declarations (interface, abstract, protocol or trait requirements) are
declarationnodes. Calls bound to them reach the declaration.overrideedges lead from the declaration to implementations. - Calls into the standard library or third-party code end at external boundary leaves, such as
ext::core.checked_add. - Calls the resolver cannot place go in
unresolved_internal. - Every node has a bottom-up
topo_layer:0for leaves, and1 + max(callee layer)for callers.
Node IDs are <file>::<qualified name>, with the file path relative to PATH. Recursive groups use scc::<first member>.
Output formats¶
| Format | Select with | Output |
|---|---|---|
text |
default, or --format text |
Human-readable summary |
json |
--format json or --json |
Compact JSON on one line, followed by a newline |
pretty-json |
--format pretty-json or --pretty-json |
Indented JSON |
bin |
--format bin or --binary |
.uhdm binary archive (see Binary format) |
If you pass several, --format wins, then --binary, --pretty-json, --json. With none, output is text.
The text format prints a header line, one line per node ([L<topo_layer>] <id> [test] (<file>:L<start>-L<end>)), one line per edge (<from> -> <to>), then one UNRESOLVED line per unresolved call:
$ uh graph crates/uhdiff-mmap
DAG: 3 files, 54 callables, 54 nodes, 241 edges, 95 external, 21 unresolved
[L3] src/lib.rs::FlatArchive.as_bytes (src/lib.rs:L909-L911)
[L4] src/lib.rs::FlatArchive.byte_len (src/lib.rs:L903-L905)
...
[L6] src/lib.rs::pod_slices_and_string_pool_round_trip_via_mmap [test] (src/lib.rs:L974-L1047)
...
src/lib.rs::FlatArchive.as_bytes -> src/lib.rs::MappedFile.as_bytes
src/lib.rs::FlatArchive.fmt -> ext::core.debug_struct
...
UNRESOLVED src/lib.rs:L142 mmap() (unresolved bare call)
UNRESOLVED src/lib.rs:L151 mapped.is_null() (unknown receiver type)
The text format omits edge dispatch kinds and confidence. It prints only the top-level graph, not the type graph that --layer both attaches. Use JSON for scripts.
Layers¶
--layer selects the graph to build.
| Value | Output |
|---|---|
calls (default) |
Call graph |
types |
Type/schema graph only, same top-level shape as the call graph |
both |
Call graph, with the type graph attached as companion_types_dag |
In the type graph, nodes are types. Edges use the dispatch kinds struct_field, embeds, implements and type_alias. Type nodes have kind: "callable". stats.callables counts types.
External boundaries¶
--boundaries sets which external leaves, and the edges into them, are kept.
| Value | Keeps |
|---|---|
all (default) |
Every external boundary |
third-party |
Only dependency boundaries. Standard library calls are dropped. |
none |
No external boundaries or edges to them |
On this repo's crates/ directory, edges drop from 46913 (all) to 22252 (third-party) to 20193 (none). Node count is the same in all three.
Tests¶
Test files and inline test callables (such as Rust #[test] functions) are included by default and marked is_test: true. --exclude-tests removes them:
Diff mode¶
Diff mode marks the nodes a change touches. A node gets changed: true when a changed line falls in its start_line..end_line range. Pick one input:
uh runs git diff -U0 <base> <head> in PATH and reads every source file from the <head> revision. Uncommitted changes are ignored. Run from the repository root so patch paths match node file paths.
uh reads sources from the working tree and takes changed lines from the unified diff, at any context size. A leading b/ is stripped from +++ paths, which must be relative to PATH. With both --diff and --base, --diff wins.
Without --bridges, diff mode returns the full graph with changed set. Filter it yourself:
Bridges¶
--bridges cuts the graph to changed nodes only:
- Edges between two changed nodes are kept.
- When a changed node reaches another only through unchanged nodes, a synthesized
bridgeedge links them. No bridge is added if a direct edge exists. - External boundaries are removed.
topo_layeris recomputed for the smaller graph.
bridge edges have an empty call_lines array:
$ uh graph . --base HEAD~5 --bridges --pretty-json | jq '[.edges[] | select(.dispatch == "bridge")][0]'
{
"from": "crates/uhdiff-review/src/graph_extract.rs::build_diff_layers",
"to": "crates/uhdiff-pipeline/src/scc.rs::build_expanded_graph",
"dispatch": "bridge",
"call_lines": []
}
--bridges changes nothing unless you also give a diff (--base, --diff).
Bridge rules¶
--bridge-include and --bridge-exclude filter edges by the languages at their ends. Each takes a comma-separated list and can repeat.
| Rule | Matches an edge when |
|---|---|
<lang> |
either end is in <lang> |
<lang_a>:<lang_b> |
one end is <lang_a> and the other <lang_b>, either direction |
same |
both ends in the same language |
cross |
ends in different languages |
- Include: keeps only
bridgeedges matching at least one rule.--bridge-includeturns on--bridgesby itself. - Exclude: drops
bridgeedges matching any rule, and direct edges between changed nodes in two languages when they match.--bridge-excludedoes not turn on--bridges, so pass both.
Language names are the adapter IDs rust, go, python, java, ts, tsx, js, jsx, cpp (C and C++), starlark, proto, swift and zig. Rules are case-insensitive. Accepted aliases: rs, py, typescript, javascript, c++, cc, cxx, bazel, bzl, protobuf. ts does not match tsx. js does not match jsx.
# Only cross-language bridges
uh graph . --base main --bridge-include cross --json
# Only bridges between Rust and proto
uh graph . --base main --bridge-include rust:proto --json
# All bridges except those touching Starlark
uh graph . --base main --bridges --bridge-exclude starlark --json
# Repeated and comma-separated forms are equivalent
uh graph . --base main --bridge-include go,proto
uh graph . --base main --bridge-include go --bridge-include proto
A malformed rule stops the run with exit code 1:
$ uh graph . --bridge-include a:b:c
uhdiff: invalid bridge pair rule 'a:b:c': too many ':'
$ uh graph . --bridge-include :go
uhdiff: invalid bridge pair rule ':go': both languages must be non-empty
$ uh graph . --bridge-include ''
uhdiff: bridge rule cannot be empty
Cache¶
uh graph keeps an on-disk cache of parsed files and graph data, so repeat runs on an unchanged or lightly changed tree are faster. The cache is on by default. The parse_cache_enabled config key (default true) controls it.
| Flag | Effect |
|---|---|
--no-cache |
Turns the cache off for this run. Cannot combine with --cache or --cache-dir. |
--cache |
Turns the cache on for this run, even if parse_cache_enabled = false. |
--cache-dir <DIR> |
Sets <DIR> as the cache root and turns the cache on. |
--cache-verify-hash |
Accepted, no effect. Cache lookups always check each file's BLAKE3 content hash. |
Without --cache-dir, the cache root is the parse_cache_dir config key or the default in Configuration. Each repository gets its own subdirectory.
The cache applies when sources come from the working tree: plain runs and --diff runs. --base/--head runs read from git and skip it. Corrupt or outdated cache files are ignored and rebuilt. uh graph reads global config from the usual file (see Configuration). It has no --config flag.
Strict mode for CI¶
--strict fails the command when any internal call stays unresolved. Full output still goes to stdout first. Then the command exits with code 1 and prints to stderr:
$ uh graph crates/uhdiff-mmap --strict --progress off > /dev/null
uhdiff: strict mode failed: 21 unresolved internal call(s)
A GitHub Actions step that saves the graph as an artifact and fails on unresolved calls:
- name: Check call resolution
run: |
uh graph . --json --strict --progress off --no-cache > graph.json
- name: Upload graph
if: always()
uses: actions/upload-artifact@v4
with:
name: call-graph
path: graph.json
To allow a set number of unresolved calls, read stats.unresolved from the JSON:
Progress output¶
uh graph reports progress on stderr, keeping stdout clean for piping.
--progress |
Behavior |
|---|---|
auto |
Animated line when stderr is a terminal; nothing otherwise |
always |
Animated line even when stderr is not a terminal |
plain |
One plain line per phase change, no ANSI escapes (for example Extracting symbols [0.0s]) |
off |
Nothing |
Without the flag, uh graph uses the progress config key. false means off. Anything else means auto. See Configuration.
JSON schema¶
Top-level keys, in order:
| Key | Type | Notes |
|---|---|---|
nodes |
array of node | Workspace nodes |
edges |
array of edge | Edges between nodes, and from nodes to boundaries |
external_boundaries |
array of boundary | External leaves |
intra_scc_edges |
array of edge | Member-level edges inside a recursive_group, including direct self-recursion. from/to are member qualified names. Omitted when empty. |
unresolved_internal |
array of unresolved call | Calls that could not be resolved |
stats |
stats | Counters |
companion_types_dag |
object | Type graph, same shape. Present only with --layer both. |
A trimmed run on a small crate:
$ uh graph crates/uhdiff-mmap --pretty-json --no-cache --progress off
{
"nodes": [
{
"id": "src/lib.rs::FlatArchive.as_bytes",
"kind": "callable",
"name": "as_bytes",
"qualified_name": "src/lib.rs::FlatArchive.as_bytes",
"file": "src/lib.rs",
"start_line": 909,
"end_line": 911,
"topo_layer": 3,
"is_test": false,
"changed": false,
"members": [
"src/lib.rs::FlatArchive.as_bytes"
]
},
...
],
"edges": [
{
"from": "src/lib.rs::FlatArchive.as_bytes",
"to": "src/lib.rs::MappedFile.as_bytes",
"dispatch": "direct",
"call_lines": [
910
]
},
...
],
"external_boundaries": [
{
"id": "ext::Option.checked_next_power_of_two",
"kind": "stdlib",
"origin": "Option",
"target": "Option.checked_next_power_of_two",
"topo_layer": 0
},
...
],
"unresolved_internal": [
{
"file": "src/lib.rs",
"line": 142,
"expression": "mmap()",
"reason": "unresolved bare call"
},
...
],
"stats": {
"files_indexed": 3,
"callables": 54,
"edges": 241,
"unresolved": 21
}
}
nodes¶
| Field | Type | Meaning |
|---|---|---|
id |
string | Unique ID: <file>::<qualified name>, or scc::<first member> for a recursive group |
kind |
string | callable, recursive_group or declaration |
name |
string | Short display name (recursive(<n>) for a recursive group) |
qualified_name |
string | Qualified display name |
file |
string | Declaring file, relative to PATH |
start_line |
integer | 1-based first line |
end_line |
integer | 1-based last line |
topo_layer |
integer | Bottom-up layer: 0 for leaves, 1 + max(callee layer) for callers |
is_test |
boolean | From a test file or an inline test block |
changed |
boolean | Touched by the diff in diff mode; always false otherwise |
members |
array of strings | Member qualified names: one for callable and declaration, two or more for recursive_group |
A recursive group, from this repository:
{
"id": "scc::seated-tree/src/parser.rs::FastParser.add_extra_link",
"kind": "recursive_group",
"name": "recursive(2)",
"qualified_name": "scc::seated-tree/src/parser.rs::FastParser.add_extra_link",
"file": "seated-tree/src/parser.rs",
"start_line": 2587,
"end_line": 2703,
"topo_layer": 2,
"is_test": false,
"changed": false,
"members": [
"seated-tree/src/parser.rs::FastParser.add_extra_link",
"seated-tree/src/parser.rs::FastParser.merge_node_links"
]
}
edges¶
| Field | Type | Meaning |
|---|---|---|
from |
string | Caller node ID |
to |
string | Callee node ID or external boundary ID |
dispatch |
string | Edge kind (see the table below) |
call_lines |
array of integers | Sorted, deduplicated 1-based call-site lines. Empty for bridge edges. |
confidence |
string | possible. Omitted when the edge is certain. |
reason |
string | Why a possible edge is not certain. Omitted when the edge is certain. |
from_member |
string | The calling member when from is a recursive group. Omitted otherwise. |
to_member |
string | The called member when to is a recursive group. Omitted otherwise. |
dispatch values:
| Value | Layer | Meaning |
|---|---|---|
direct |
calls | Static call to a concrete function or method |
dynamic_dispatch |
calls | Interface, trait or virtual dispatch to implementers when the bound declaration is not a workspace node (for example, a third-party interface), or when the receiver admits only some implementations |
non_virtual |
calls | Call bound past overrides (super.m(), Base.m(self)): only the named method runs |
override |
calls | Not a call. Links an overridable method or declaration to an override or implementation that may run in its place. |
generated |
calls | Call through generated code: a gRPC stub method to its proto rpc, or a proto rpc to the implementing server method |
function_ref |
calls | Indirect function-value reference: callback argument, higher-order function value, handler registration, or vtable/dispatch-table entry. Only the uh review UI adds these; uh graph does not emit them. |
bridge |
calls, types | Synthesized by --bridges across unchanged intermediates |
struct_field |
types | A struct or class field refers to another type |
embeds |
types | A struct or class embeds or extends another type |
implements |
types | A struct or class implements an interface or trait |
type_alias |
types | A type alias points to its target |
reason values (a closed set; see Languages for when each applies): ambiguous-overload, dispatch-no-evidence, fallback-name-match, unresolved-include, alternative-definition, reassignable-binding, decorator-wrapped, external-shadowing, union-member.
A possible edge:
{
"from": "src/cache.rs::binary_round_trip_preserves_every_field",
"to": "src/cache.rs::decode_extracted_file",
"dispatch": "direct",
"call_lines": [6349, 6359],
"confidence": "possible",
"reason": "alternative-definition"
}
To list only proven edges, select edges with no confidence key:
external_boundaries¶
| Field | Type | Meaning |
|---|---|---|
id |
string | Boundary ID, the to of edges that point at it (for example ext::clap.Parser.command) |
kind |
string | stdlib, dependency, interface or generated |
origin |
string | Package or library (for example clap) |
target |
string | Target symbol expression (for example clap.Parser.command) |
topo_layer |
integer | Always 0 |
kind values:
| Value | Meaning |
|---|---|
stdlib |
Language standard library |
dependency |
Third-party code outside the workspace |
interface |
Abstract workspace interface method with no workspace implementation (ext::iface::<file>::<Iface>.<method>) |
generated |
Generated member of a workspace declaration, such as a proto message accessor (ext::generated::<proto type>.<member>) |
unresolved_internal¶
| Field | Type | Meaning |
|---|---|---|
file |
string | File containing the call, relative to PATH |
line |
integer | 1-based line |
expression |
string | Call expression text |
reason |
string | Free-text reason, for example unresolved bare call or unknown receiver type |
stats¶
| Field | Type | Meaning |
|---|---|---|
files_indexed |
integer | Files indexed |
callables |
integer | Callables indexed (types, in the type graph) |
edges |
integer | Edges in edges |
unresolved |
integer | Unresolved internal calls |
Binary format (.uhdm)¶
--binary (or --format bin) writes the same graph as a flat binary archive. Strings are stored once in a shared pool. Rows refer to them by u32 index, so the file is much smaller than JSON on large graphs. Decoding returns the same graph.
The archive layout:
| Part | Contents |
|---|---|
| Header (32 bytes) | Magic UHDM, format version (u32, currently 1), section count (u32), flags (u32, 0), total file length (u64), FNV-1a 64-bit checksum over the header prefix and section directory (u64) |
| Section directory | One 32-byte entry per section: tag (u32), padding (u32), offset (u64), byte length (u64), element count (u64) |
| Sections | Payloads, each aligned to 8 bytes |
| Trailer | The 8 bytes UHDMEND!, which detect truncation |
Section tags: 1 nodes, 2 member string IDs, 3 edges, 4 call-site lines, 5 external boundaries, 6 intra-SCC edges, 7 unresolved calls, 8 stats, 9 string-pool offsets, 10 string-pool bytes, 12 nested .uhdm archive for companion_types_dag. Integers use the host's native byte order, which is little-endian on every release platform.
$ uh graph crates/uhdiff-mmap --binary --progress off > graph.uhdm
$ xxd graph.uhdm | head -2
00000000: 5548 444d 0100 0000 0a00 0000 0000 0000 UHDM............
00000010: a851 0000 0000 0000 fd1f 5913 8868 abf8 .Q........Y..h..
From Rust, the uhdiff-report crate decodes archives with Dag::read_binary(&bytes) or Dag::open_binary(path). Row layouts are in crates/uhdiff-mmap/src/rows.rs.
uh parse¶
uh parse <PATH> runs one file through its language extractor and prints the result. It does no cross-file resolution. The extension or file name picks the language (see Languages). Unsupported files exit with code 1:
The text format lists the package, imports, types, and each callable with its calls:
$ uh parse crates/uhdiff-mmap/src/lib.rs
crates/uhdiff-mmap/src/lib.rs: package <none>
import L9: "core"
import L10: "core::mem"
...
type L46: interface Pod
type L122: struct unix_mmap.RawMmap
type L181: enum MappedBacking
...
fn L62-L70: pod_as_bytes
call L63: items.len().saturating_mul()
call L63: core.slice.len()
call L63: size_of.size_of[T]()
call L69: slice.from_raw_parts()
fn L73-L91: pod_from_bytes
...
Lines have these shapes: import L<n>: [alias] "<path>", type L<n>: <kind> <name> (with = <target> for aliases), fn L<start>-L<end>: [(<owner>).]<name>, and call L<n>: [<qualifier>.]<callee>[<type args>]().
--format pretty-json (or --pretty-json) prints the full extracted file as JSON. It has the top-level keys package, imports, types, callables, bindings, calls, generated, implementations, trait_impls, stdlib_blanket_traits and mod_decls. Each span has start_line, end_line, start_byte and end_byte. This is the extractor's internal representation, with more detail than the text view:
uh parse supports only text and pretty-json.