| 1 | // Copyright 2026 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package graphfmt serializes graphs to external representations. |
| 6 | package graphfmt |
| 7 | |
| 8 | import ( |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "os/exec" |
| 12 | "strings" |
| 13 | |
| 14 | "golang.org/x/tools/internal/graph" |
| 15 | ) |
| 16 | |
| 17 | // Dot contains options for generating a Graphviz Dot graph from a |
| 18 | // [graph.Graph]. |
| 19 | type Dot[NodeID comparable] struct { |
| 20 | // Name is the name given to the graph. Usually this can be |
| 21 | // left blank. |
| 22 | Name string |
| 23 | |
| 24 | // Label returns the string to use as a label for the given |
| 25 | // node. If nil, nodes are labeled with their node numbers. |
| 26 | Label func(node NodeID) string |
| 27 | |
| 28 | // NodeAttrs, if non-nil, returns a set of attributes for a |
| 29 | // node. If this includes a "label" attribute, it overrides |
| 30 | // the label returned by Label. |
| 31 | NodeAttrs func(node NodeID) []DotAttr |
| 32 | |
| 33 | // EdgeAttrs, if non-nil, returns a set of attributes for an |
| 34 | // edge. |
| 35 | EdgeAttrs func(from, to NodeID) []DotAttr |
| 36 | |
| 37 | // ClusterOf, if non-nil, returns the cluster of a node, or nil if the node |
| 38 | // should not be in a cluster. Multiple nodes with the same cluster will be |
| 39 | // arranged together and enclosed in a box. |
| 40 | ClusterOf func(node NodeID) *DotCluster |
| 41 | } |
| 42 | |
| 43 | // DotAttr is an attribute for a Dot node or edge. |
| 44 | type DotAttr struct { |
| 45 | Name string |
| 46 | |
| 47 | // Val is the value of this attribute. It may be a string |
| 48 | // (which will be escaped), bool, int, uint, float64 or |
| 49 | // DotLiteral. |
| 50 | Val any |
| 51 | } |
| 52 | |
| 53 | // DotLiteral is a string literal that should be passed to dot |
| 54 | // unescaped. |
| 55 | type DotLiteral string |
| 56 | |
| 57 | // DotCluster represents a cluster of nodes arranged together. |
| 58 | type DotCluster struct { |
| 59 | Label string |
| 60 | Attrs []DotAttr |
| 61 | } |
| 62 | |
| 63 | func defaultLabel[NodeID comparable](node NodeID) string { |
| 64 | return fmt.Sprint(node) |
| 65 | } |
| 66 | |
| 67 | // Sprint returns the Dot form of g as a string. |
| 68 | func (d Dot[NodeID]) Sprint(g graph.Graph[NodeID]) string { |
| 69 | w := new(strings.Builder) |
| 70 | |
| 71 | nodeLabel := d.Label |
| 72 | if nodeLabel == nil { |
| 73 | nodeLabel = defaultLabel |
| 74 | } |
| 75 | |
| 76 | fmt.Fprintf(w, "digraph %s {\n", dotString(d.Name)) |
| 77 | |
| 78 | // Collect nodes by cluster. |
| 79 | type cluster struct { |
| 80 | c *DotCluster |
| 81 | nodes []NodeID |
| 82 | } |
| 83 | var clusters []cluster |
| 84 | clusterIDs := make(map[*DotCluster]int) |
| 85 | nodeNums := make(map[NodeID]int) |
| 86 | for nid := range g.Nodes() { |
| 87 | var c *DotCluster |
| 88 | if d.ClusterOf != nil { |
| 89 | c = d.ClusterOf(nid) |
| 90 | } |
| 91 | id, ok := clusterIDs[c] |
| 92 | if !ok { |
| 93 | id = len(clusters) |
| 94 | clusterIDs[c] = id |
| 95 | clusters = append(clusters, cluster{c: c}) |
| 96 | } |
| 97 | clusters[id].nodes = append(clusters[id].nodes, nid) |
| 98 | nodeNums[nid] = len(nodeNums) |
| 99 | } |
| 100 | |
| 101 | // Emit each cluster. |
| 102 | for cid, c := range clusters { |
| 103 | if c.c != nil { |
| 104 | fmt.Fprintf(w, "subgraph cluster_%d {\n", cid) |
| 105 | if attrs := formatAttrs(c.c.Attrs, c.c.Label); attrs != "" { |
| 106 | fmt.Fprintf(w, "graph %s;", attrs) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // Emit nodes. We don't emit edges yet because an edge may have a |
| 111 | // forward-reference, which could define the target node in the wrong |
| 112 | // cluster. |
| 113 | for _, nid := range c.nodes { |
| 114 | // Define node. |
| 115 | var attrList []DotAttr |
| 116 | var label string |
| 117 | if d.NodeAttrs != nil { |
| 118 | attrList = d.NodeAttrs(nid) |
| 119 | } |
| 120 | if nodeLabel != nil { |
| 121 | label = nodeLabel(nid) |
| 122 | } |
| 123 | fmt.Fprintf(w, "n%d%s;\n", nodeNums[nid], formatAttrs(attrList, label)) |
| 124 | } |
| 125 | |
| 126 | if c.c != nil { |
| 127 | fmt.Fprintf(w, "}\n") |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // Emit edges. |
| 132 | for nid := range g.Nodes() { |
| 133 | for succ := range g.Out(nid) { |
| 134 | var attrs string |
| 135 | if d.EdgeAttrs != nil { |
| 136 | attrs = formatAttrs(d.EdgeAttrs(nid, succ), "") |
| 137 | } |
| 138 | fmt.Fprintf(w, "n%d -> n%d%s;\n", nodeNums[nid], nodeNums[succ], attrs) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fmt.Fprintf(w, "}\n") |
| 143 | |
| 144 | return w.String() |
| 145 | } |
| 146 | |
| 147 | // SVG attempts to render g to an SVG. |
| 148 | func (d Dot[NodeID]) SVG(w io.Writer, g graph.Graph[NodeID]) error { |
| 149 | // Check that we can run Dot at all. |
| 150 | dot := exec.Command("dot", "-V") |
| 151 | if err := dot.Run(); err != nil { |
| 152 | return fmt.Errorf("cannot run dot: %s", err) |
| 153 | } |
| 154 | |
| 155 | // Convert to SVG. |
| 156 | // |
| 157 | // TODO: Consider lifting nice graph viewer from go.dev/cl/192706 |
| 158 | dot = exec.Command("dot", "-Tsvg", "-") |
| 159 | in, err := dot.StdinPipe() |
| 160 | if err != nil { |
| 161 | return fmt.Errorf("running dot: %s", err) |
| 162 | } |
| 163 | dot.Stdout = w |
| 164 | if err := dot.Start(); err != nil { |
| 165 | return fmt.Errorf("running dot: %s", err) |
| 166 | } |
| 167 | _, err = in.Write([]byte(d.Sprint(g))) |
| 168 | in.Close() |
| 169 | if err != nil { |
| 170 | // Let Dot exit, but ignore any errors from it. |
| 171 | dot.Wait() |
| 172 | return err |
| 173 | } |
| 174 | if err := dot.Wait(); err != nil { |
| 175 | if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { |
| 176 | return fmt.Errorf("running dot: %s\n%s", err, err.Stderr) |
| 177 | } |
| 178 | return fmt.Errorf("running dot: %s", err) |
| 179 | } |
| 180 | return nil |
| 181 | } |
| 182 | |
| 183 | var dotStringer = strings.NewReplacer( |
| 184 | "\n", `\n`, |
| 185 | `\`, `\\`, |
| 186 | `"`, `\"`, |
| 187 | `{`, `\{`, |
| 188 | `}`, `\}`, |
| 189 | `<`, `\<`, |
| 190 | `>`, `\>`, |
| 191 | `|`, `\|`, |
| 192 | ) |
| 193 | |
| 194 | // dotString returns s as a quoted dot string. |
| 195 | func dotString(s string) string { |
| 196 | var buf strings.Builder |
| 197 | buf.WriteByte('"') |
| 198 | dotStringer.WriteString(&buf, s) |
| 199 | buf.WriteByte('"') |
| 200 | return buf.String() |
| 201 | } |
| 202 | |
| 203 | // formatAttrs formats attrs as a dot attribute set, including the surrounding |
| 204 | // brackets. If "label" is not present in attrs and the label argument is not |
| 205 | // "", it adds the given label attribute. If attrs is empty and label is "", it |
| 206 | // returns an empty string. |
| 207 | func formatAttrs(attrs []DotAttr, label string) string { |
| 208 | if len(attrs) == 0 && label == "" { |
| 209 | return "" |
| 210 | } |
| 211 | var buf strings.Builder |
| 212 | buf.WriteString(" [") |
| 213 | haveLabel := false |
| 214 | for i, attr := range attrs { |
| 215 | if i > 0 { |
| 216 | buf.WriteString(",") |
| 217 | } |
| 218 | formatAttr(&buf, attr) |
| 219 | if attr.Name == "label" { |
| 220 | haveLabel = true |
| 221 | } |
| 222 | } |
| 223 | if !haveLabel && label != "" { |
| 224 | if len(attrs) > 0 { |
| 225 | buf.WriteString(",") |
| 226 | } |
| 227 | formatAttr(&buf, DotAttr{"label", label}) |
| 228 | } |
| 229 | buf.WriteString("]") |
| 230 | return buf.String() |
| 231 | } |
| 232 | |
| 233 | func formatAttr(buf *strings.Builder, attr DotAttr) { |
| 234 | buf.WriteString(attr.Name) |
| 235 | buf.WriteString("=") |
| 236 | switch val := attr.Val.(type) { |
| 237 | case string: |
| 238 | buf.WriteString(dotString(val)) |
| 239 | case bool, int, uint, float64: |
| 240 | fmt.Fprintf(buf, "%v", val) |
| 241 | case DotLiteral: |
| 242 | buf.WriteString(string(val)) |
| 243 | default: |
| 244 | panic(fmt.Sprintf("dot attribute %s had unknown type %T", attr.Name, attr.Val)) |
| 245 | } |
| 246 | } |