///|
/// A node in a resolved CUE package dependency graph.
#derive(Eq, Debug)
pub(all) struct PackageGraphNode {
id : String
label : String
pkg_name : String
is_root : Bool
is_stdlib : Bool
file_count : Int32
}
///|
/// A directed dependency edge (`from` imports `to`) in a CUE package dependency graph.
#derive(Eq, Debug)
pub(all) struct PackageGraphEdge {
from : String
to : String
is_stdlib : Bool
}
///|
/// Resolved, deduplicated, and deterministically ordered package dependency graph.
#derive(Eq, Debug)
pub(all) struct PackageDepGraph {
module_name : String?
root_id : String
nodes : Array[PackageGraphNode]
edges : Array[PackageGraphEdge]
}
///|
fn last_segment_slash(path : String) -> String {
let chars = path.to_array()
let mut last_slash : Int32 = -1
for i, ch in chars {
if ch == '/' {
last_slash = i
}
}
let buf = StringBuilder()
for i in (last_slash + 1).. (String, String?) {
let chars = raw.to_array()
let mut colon_idx : Int32 = -1
for i, ch in chars {
if ch == ':' {
colon_idx = i
break
}
}
if colon_idx < 0 {
return (raw, None)
}
let base_buf = StringBuilder()
for i in 0.. String {
if dep.import_path.is_empty() {
return ":" + dep.pkg_name
}
if dep.import_path.contains(":") ||
dep.pkg_name.is_empty() ||
dep.pkg_name == last_segment_slash(dep.import_path) {
dep.import_path
} else {
"\{dep.import_path}:\{dep.pkg_name}"
}
}
///|
fn dep_base_and_pkg(dep : @eval.PackageUnit) -> (String, String) {
let (base, explicit_pkg) = split_import_qualifier(dep.import_path)
let pkg = match explicit_pkg {
Some(q) => if !dep.pkg_name.is_empty() { dep.pkg_name } else { q }
None => dep.pkg_name
}
(base, pkg)
}
///|
fn resolve_import_target(
raw_spec : String,
deps : Array[@eval.PackageUnit],
root_id : String,
root_import_path : String?,
root_pkg_name : String,
) -> (String, Bool)? {
if is_stdlib_import(raw_spec) {
return Some((raw_spec, true))
}
let (spec_base, explicit_pkg) = split_import_qualifier(raw_spec)
let spec_pkg = match explicit_pkg {
Some(q) => q
None => last_segment_slash(spec_base)
}
// 1. Exact import_path match when qualifier semantics align
for dep in deps {
let (_, dep_pkg) = dep_base_and_pkg(dep)
if dep.import_path == raw_spec &&
(explicit_pkg is Some(_) || dep_pkg == spec_pkg || dep_pkg.is_empty()) {
return Some((dep_node_id(dep), false))
}
}
// 2. Canonical (base_path, pkg_name) match across :pkg and default-pkg forms
for dep in deps {
let (dep_base, dep_pkg) = dep_base_and_pkg(dep)
if dep_base == spec_base && dep_pkg == spec_pkg {
return Some((dep_node_id(dep), false))
}
}
// 3. Fallback for synthetic deps without pkg_name populated
if explicit_pkg is None {
for dep in deps {
let (dep_base, _) = dep_base_and_pkg(dep)
if dep_base == spec_base && dep.pkg_name.is_empty() {
return Some((dep_node_id(dep), false))
}
}
}
// 4. Match root package if a manually constructed graph contains a back-edge
match root_import_path {
Some(rp) => {
let (r_base, r_explicit) = split_import_qualifier(rp)
let r_pkg = match r_explicit {
Some(q) => q
None => root_pkg_name
}
if r_base == spec_base && (r_pkg == spec_pkg || root_pkg_name == spec_pkg) {
return Some((root_id, false))
}
}
None => ()
}
None
}
///|
fn add_node_dedup(
nodes : Array[PackageGraphNode],
seen : Map[String, Bool],
node : PackageGraphNode,
) -> Unit {
if !seen.contains(node.id) {
seen.set(node.id, true)
nodes.push(node)
}
}
///|
fn add_edge_dedup(
edges : Array[PackageGraphEdge],
seen : Map[String, Bool],
edge : PackageGraphEdge,
) -> Unit {
let key = "\{edge.from}\u{0000}\{edge.to}"
if !seen.contains(key) {
seen.set(key, true)
edges.push(edge)
}
}
///|
fn alloc_stdlib_node_id(
target_id : String,
seen_local_ids : Map[String, Bool],
std_node_ids : Map[String, String],
used_std_ids : Map[String, Bool],
) -> String {
match std_node_ids.get(target_id) {
Some(existing) => return existing
None => ()
}
let mut candidate = target_id
if seen_local_ids.contains(candidate) || used_std_ids.contains(candidate) {
candidate = "stdlib:" + target_id
let mut suffix : Int32 = 2
while seen_local_ids.contains(candidate) || used_std_ids.contains(candidate) {
candidate = "stdlib#\{suffix}:" + target_id
suffix += 1
}
}
std_node_ids.set(target_id, candidate)
used_std_ids.set(candidate, true)
candidate
}
///|
fn collect_file_imports(
owner_id : String,
files : Array[@syntax.File],
deps : Array[@eval.PackageUnit],
root_id : String,
root_import_path : String?,
root_pkg_name : String,
include_stdlib : Bool,
nodes : Array[PackageGraphNode],
seen_nodes : Map[String, Bool],
seen_local_ids : Map[String, Bool],
std_node_ids : Map[String, String],
used_std_ids : Map[String, Bool],
edges : Array[PackageGraphEdge],
seen_edges : Map[String, Bool],
) -> Unit {
for file in files {
for imp in file.imports {
for spec in imp.specs {
match
resolve_import_target(
spec.path,
deps,
root_id,
root_import_path,
root_pkg_name,
) {
None => ()
Some((target_id, is_std)) =>
if is_std {
if include_stdlib {
let std_node_id = alloc_stdlib_node_id(
target_id, seen_local_ids, std_node_ids, used_std_ids,
)
add_node_dedup(nodes, seen_nodes, {
id: std_node_id,
label: target_id,
pkg_name: last_segment_slash(target_id),
is_root: false,
is_stdlib: true,
file_count: 0,
})
add_edge_dedup(edges, seen_edges, {
from: owner_id,
to: std_node_id,
is_stdlib: true,
})
}
} else {
add_edge_dedup(edges, seen_edges, {
from: owner_id,
to: target_id,
is_stdlib: false,
})
}
}
}
}
}
}
///|
/// Builds a deduplicated, deterministically sorted `PackageDepGraph` from a
/// resolved CUE package graph.
pub fn build_dep_graph(
graph : ResolvedPackageGraph,
include_stdlib~ : Bool = false,
) -> PackageDepGraph {
let module_name = graph.manifest.map(fn(m) { m.raw_module })
let root_id = match graph.root.import_path {
Some(p) => p
None => ":" + graph.root.pkg_name
}
let nodes : Array[PackageGraphNode] = []
let seen_nodes : Map[String, Bool] = Map([])
let seen_local_ids : Map[String, Bool] = Map([])
let std_node_ids : Map[String, String] = Map([])
let used_std_ids : Map[String, Bool] = Map([])
let edges : Array[PackageGraphEdge] = []
let seen_edges : Map[String, Bool] = Map([])
seen_local_ids.set(root_id, true)
add_node_dedup(nodes, seen_nodes, {
id: root_id,
label: root_id,
pkg_name: graph.root.pkg_name,
is_root: true,
is_stdlib: false,
file_count: graph.root.files.length(),
})
for dep in graph.deps {
let dep_id = dep_node_id(dep)
seen_local_ids.set(dep_id, true)
add_node_dedup(nodes, seen_nodes, {
id: dep_id,
label: dep_id,
pkg_name: dep.pkg_name,
is_root: false,
is_stdlib: false,
file_count: dep.files.length(),
})
}
let root_asts = graph.root.files.map(fn(f) { f.ast })
collect_file_imports(
root_id,
root_asts,
graph.deps,
root_id,
graph.root.import_path,
graph.root.pkg_name,
include_stdlib,
nodes,
seen_nodes,
seen_local_ids,
std_node_ids,
used_std_ids,
edges,
seen_edges,
)
for dep in graph.deps {
collect_file_imports(
dep_node_id(dep),
dep.files,
graph.deps,
root_id,
graph.root.import_path,
graph.root.pkg_name,
include_stdlib,
nodes,
seen_nodes,
seen_local_ids,
std_node_ids,
used_std_ids,
edges,
seen_edges,
)
}
nodes.sort_by(fn(a, b) {
if a.is_root != b.is_root {
if a.is_root {
-1
} else {
1
}
} else {
@eval.compare_cue_string(a.id, b.id)
}
})
edges.sort_by(fn(a, b) {
let c = @eval.compare_cue_string(a.from, b.from)
if c != 0 {
c
} else {
@eval.compare_cue_string(a.to, b.to)
}
})
{ module_name, root_id, nodes, edges, }
}
///|
fn graph_utf8_char_len(ch : Char) -> Int64 {
let code = ch.to_int()
if code < 0x80 {
1L
} else if code < 0x800 {
2L
} else if code < 0x10000 {
3L
} else {
4L
}
}
///|
priv struct GraphBoundedWriter {
buf : StringBuilder
max_bytes : Int64?
mut used_bytes : Int64
mut exceeded : Bool
}
///|
fn GraphBoundedWriter::new(max_bytes : Int64?) -> GraphBoundedWriter {
let exceeded = match max_bytes {
Some(limit) => limit < 0L
None => false
}
{ buf: StringBuilder(), max_bytes, used_bytes: 0L, exceeded, }
}
///|
fn GraphBoundedWriter::write_char(self : GraphBoundedWriter, ch : Char) -> Unit {
if self.exceeded {
return
}
self.used_bytes += graph_utf8_char_len(ch)
match self.max_bytes {
Some(limit) =>
if self.used_bytes > limit {
self.exceeded = true
return
}
None => ()
}
self.buf.write_char(ch)
}
///|
fn GraphBoundedWriter::write_string(
self : GraphBoundedWriter,
s : String,
) -> Unit {
if self.exceeded {
return
}
match self.max_bytes {
Some(limit) => {
for ch in s {
self.used_bytes += graph_utf8_char_len(ch)
if self.used_bytes > limit {
self.exceeded = true
return
}
}
self.buf.write_string(s)
}
None => self.buf.write_string(s)
}
}
///|
fn GraphBoundedWriter::write_spaces(
self : GraphBoundedWriter,
indent : Int32,
depth : Int32,
) -> Unit {
if self.exceeded || indent <= 0 || depth <= 0 {
return
}
let spaces = indent.to_int64() * depth.to_int64()
self.used_bytes += spaces
match self.max_bytes {
Some(limit) =>
if self.used_bytes > limit {
self.exceeded = true
return
}
None => ()
}
let mut rem = spaces
while rem > 0L {
self.buf.write_char(' ')
rem -= 1L
}
}
///|
fn GraphBoundedWriter::finish(
self : GraphBoundedWriter,
limit_bytes : Int32,
) -> Result[String, @eval.LimitError] {
if self.exceeded {
let reported = if self.used_bytes > 2_147_483_647L {
2_147_483_647
} else {
self.used_bytes.to_int()
}
Err(@eval.LimitError::OutputBytesExceeded(reported, limit_bytes))
} else {
Ok(self.buf.to_string())
}
}
///|
fn write_mermaid_label(w : GraphBoundedWriter, s : String) -> Unit {
for ch in s {
if w.exceeded {
return
}
match ch {
'"' => w.write_string("#quot;")
'\\' => w.write_string("\\\\")
'\n' => w.write_string("\\n")
'\r' => w.write_string("\\r")
'\t' => w.write_string("\\t")
_ => if ch.to_int() < 0x20 { w.write_char(' ') } else { w.write_char(ch) }
}
}
}
///|
fn write_dot_quoted(w : GraphBoundedWriter, s : String) -> Unit {
w.write_char('"')
for ch in s {
if w.exceeded {
return
}
match ch {
'"' => w.write_string("\\\"")
'\\' => w.write_string("\\\\")
'\n' => w.write_string("\\n")
'\r' => w.write_string("\\r")
'\t' => w.write_string("\\t")
_ => if ch.to_int() < 0x20 { w.write_char(' ') } else { w.write_char(ch) }
}
}
w.write_char('"')
}
///|
fn format_graph_mermaid_impl(
w : GraphBoundedWriter,
graph : PackageDepGraph,
) -> Unit {
w.write_string("graph TD\n")
let id_map : Map[String, String] = Map([])
let mut next_idx : Int32 = 0
for node in graph.nodes {
if w.exceeded {
return
}
if !id_map.contains(node.id) {
let mid = "n\{next_idx}"
next_idx += 1
id_map.set(node.id, mid)
w.write_string(" ")
w.write_string(mid)
w.write_string("[\"")
write_mermaid_label(w, node.label)
w.write_string("\"]\n")
}
}
for edge in graph.edges {
if w.exceeded {
return
}
if !id_map.contains(edge.from) {
let mid = "n\{next_idx}"
next_idx += 1
id_map.set(edge.from, mid)
w.write_string(" ")
w.write_string(mid)
w.write_string("[\"")
write_mermaid_label(w, edge.from)
w.write_string("\"]\n")
}
if !id_map.contains(edge.to) {
let mid = "n\{next_idx}"
next_idx += 1
id_map.set(edge.to, mid)
w.write_string(" ")
w.write_string(mid)
w.write_string("[\"")
write_mermaid_label(w, edge.to)
w.write_string("\"]\n")
}
let from_mid = id_map.get(edge.from).unwrap()
let to_mid = id_map.get(edge.to).unwrap()
w.write_string(" ")
w.write_string(from_mid)
if edge.is_stdlib {
w.write_string(" -.-> ")
} else {
w.write_string(" --> ")
}
w.write_string(to_mid)
w.write_char('\n')
}
w.write_string(
" classDef root fill:#e0f2fe,stroke:#0284c7,stroke-width:2px\n",
)
w.write_string(
" classDef stdlib fill:#f3f4f6,stroke:#6b7280,stroke-dasharray:5 5\n",
)
for node in graph.nodes {
if w.exceeded {
return
}
match id_map.get(node.id) {
Some(mid) =>
if node.is_root {
w.write_string(" class ")
w.write_string(mid)
w.write_string(" root\n")
} else if node.is_stdlib {
w.write_string(" class ")
w.write_string(mid)
w.write_string(" stdlib\n")
}
None => ()
}
}
}
///|
/// Formats a `PackageDepGraph` as a Mermaid `graph TD` flowchart.
pub fn format_graph_mermaid(graph : PackageDepGraph) -> String {
let w = GraphBoundedWriter::new(None)
format_graph_mermaid_impl(w, graph)
w.buf.to_string()
}
///|
/// Formats a `PackageDepGraph` as a Mermaid `graph TD` flowchart while
/// enforcing `max_output_bytes`.
pub fn format_graph_mermaid_bounded(
graph : PackageDepGraph,
max_output_bytes : Int32,
) -> Result[String, @eval.LimitError] {
let w = GraphBoundedWriter::new(Some(max_output_bytes.to_int64()))
format_graph_mermaid_impl(w, graph)
w.finish(max_output_bytes)
}
///|
fn format_graph_dot_impl(
w : GraphBoundedWriter,
graph : PackageDepGraph,
) -> Unit {
w.write_string("digraph cuesmith_deps {\n")
w.write_string(" rankdir=LR;\n")
let id_map : Map[String, String] = Map([])
let mut next_idx : Int32 = 0
for node in graph.nodes {
if w.exceeded {
return
}
if !id_map.contains(node.id) {
let did = "n\{next_idx}"
next_idx += 1
id_map.set(node.id, did)
w.write_string(" ")
w.write_string(did)
w.write_string(" [label=")
write_dot_quoted(w, node.label)
if node.is_root {
w.write_string(", style=\"bold,filled\", fillcolor=\"#e0f2fe\"")
} else if node.is_stdlib {
w.write_string(", style=\"dashed,filled\", fillcolor=\"#f3f4f6\"")
}
w.write_string("];\n")
}
}
for edge in graph.edges {
if w.exceeded {
return
}
if !id_map.contains(edge.from) {
let did = "n\{next_idx}"
next_idx += 1
id_map.set(edge.from, did)
w.write_string(" ")
w.write_string(did)
w.write_string(" [label=")
write_dot_quoted(w, edge.from)
w.write_string("];\n")
}
if !id_map.contains(edge.to) {
let did = "n\{next_idx}"
next_idx += 1
id_map.set(edge.to, did)
w.write_string(" ")
w.write_string(did)
w.write_string(" [label=")
write_dot_quoted(w, edge.to)
w.write_string("];\n")
}
let from_did = id_map.get(edge.from).unwrap()
let to_did = id_map.get(edge.to).unwrap()
w.write_string(" ")
w.write_string(from_did)
w.write_string(" -> ")
w.write_string(to_did)
if edge.is_stdlib {
w.write_string(" [style=dashed]")
}
w.write_string(";\n")
}
w.write_string("}\n")
}
///|
/// Formats a `PackageDepGraph` as a Graphviz DOT `digraph cuesmith_deps`.
pub fn format_graph_dot(graph : PackageDepGraph) -> String {
let w = GraphBoundedWriter::new(None)
format_graph_dot_impl(w, graph)
w.buf.to_string()
}
///|
/// Formats a `PackageDepGraph` as a Graphviz DOT `digraph cuesmith_deps` while
/// enforcing `max_output_bytes`.
pub fn format_graph_dot_bounded(
graph : PackageDepGraph,
max_output_bytes : Int32,
) -> Result[String, @eval.LimitError] {
let w = GraphBoundedWriter::new(Some(max_output_bytes.to_int64()))
format_graph_dot_impl(w, graph)
w.finish(max_output_bytes)
}
///|
fn json_hex_digit(n : Int32) -> Char {
if n < 10 {
(n + '0'.to_int()).unsafe_to_char()
} else {
(n - 10 + 'a'.to_int()).unsafe_to_char()
}
}
///|
fn write_json_str(w : GraphBoundedWriter, s : String) -> Unit {
if w.exceeded {
return
}
w.write_char('"')
for ch in s {
if w.exceeded {
return
}
match ch {
'"' => w.write_string("\\\"")
'\\' => w.write_string("\\\\")
'\b' => w.write_string("\\b")
'\u{0C}' => w.write_string("\\f")
'\n' => w.write_string("\\n")
'\r' => w.write_string("\\r")
'\t' => w.write_string("\\t")
_ => {
let code = ch.to_int()
if code < 0x20 {
let hi = (code >> 4) & 0xF
let lo = code & 0xF
w.write_string("\\u00")
w.write_char(json_hex_digit(hi))
w.write_char(json_hex_digit(lo))
} else {
w.write_char(ch)
}
}
}
}
w.write_char('"')
}
///|
fn write_json_indent(
w : GraphBoundedWriter,
indent : Int32,
depth : Int32,
) -> Unit {
w.write_spaces(indent, depth)
}
///|
fn write_json_nl(w : GraphBoundedWriter, indent : Int32) -> Unit {
if indent > 0 {
w.write_char('\n')
}
}
///|
fn write_json_colon(w : GraphBoundedWriter, indent : Int32) -> Unit {
if indent > 0 {
w.write_string(": ")
} else {
w.write_char(':')
}
}
///|
fn write_json_key(
w : GraphBoundedWriter,
indent : Int32,
depth : Int32,
key : String,
) -> Unit {
write_json_indent(w, indent, depth)
write_json_str(w, key)
write_json_colon(w, indent)
}
///|
fn format_graph_json_impl(
w : GraphBoundedWriter,
graph : PackageDepGraph,
indent : Int32,
) -> Unit {
let eff_indent : Int32 = if indent < 0 {
0
} else if indent > 16 {
16
} else {
indent
}
w.write_char('{')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 1, "module")
match graph.module_name {
Some(m) => write_json_str(w, m)
None => w.write_string("null")
}
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 1, "root")
write_json_str(w, graph.root_id)
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 1, "nodes")
if w.exceeded {
return
}
if graph.nodes.is_empty() {
w.write_string("[]")
} else {
w.write_char('[')
write_json_nl(w, eff_indent)
for i, node in graph.nodes {
if w.exceeded {
return
}
if i > 0 {
w.write_char(',')
write_json_nl(w, eff_indent)
}
write_json_indent(w, eff_indent, 2)
w.write_char('{')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "id")
write_json_str(w, node.id)
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "label")
write_json_str(w, node.label)
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "pkg_name")
write_json_str(w, node.pkg_name)
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "is_root")
w.write_string(if node.is_root { "true" } else { "false" })
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "is_stdlib")
w.write_string(if node.is_stdlib { "true" } else { "false" })
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "file_count")
w.write_string(node.file_count.to_string())
write_json_nl(w, eff_indent)
write_json_indent(w, eff_indent, 2)
w.write_char('}')
}
write_json_nl(w, eff_indent)
write_json_indent(w, eff_indent, 1)
w.write_char(']')
}
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 1, "edges")
if w.exceeded {
return
}
if graph.edges.is_empty() {
w.write_string("[]")
} else {
w.write_char('[')
write_json_nl(w, eff_indent)
for i, edge in graph.edges {
if w.exceeded {
return
}
if i > 0 {
w.write_char(',')
write_json_nl(w, eff_indent)
}
write_json_indent(w, eff_indent, 2)
w.write_char('{')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "from")
write_json_str(w, edge.from)
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "to")
write_json_str(w, edge.to)
w.write_char(',')
write_json_nl(w, eff_indent)
write_json_key(w, eff_indent, 3, "is_stdlib")
w.write_string(if edge.is_stdlib { "true" } else { "false" })
write_json_nl(w, eff_indent)
write_json_indent(w, eff_indent, 2)
w.write_char('}')
}
write_json_nl(w, eff_indent)
write_json_indent(w, eff_indent, 1)
w.write_char(']')
}
write_json_nl(w, eff_indent)
w.write_char('}')
}
///|
/// Formats a `PackageDepGraph` as strict RFC 8259 JSON.
pub fn format_graph_json(
graph : PackageDepGraph,
indent~ : Int32 = 2,
) -> String {
let w = GraphBoundedWriter::new(None)
format_graph_json_impl(w, graph, indent)
w.buf.to_string()
}
///|
/// Formats a `PackageDepGraph` as strict RFC 8259 JSON while enforcing
/// `max_output_bytes`.
pub fn format_graph_json_bounded(
graph : PackageDepGraph,
max_output_bytes : Int32,
indent~ : Int32 = 2,
) -> Result[String, @eval.LimitError] {
let w = GraphBoundedWriter::new(Some(max_output_bytes.to_int64()))
format_graph_json_impl(w, graph, indent)
w.finish(max_output_bytes)
}