File size: 4,826 Bytes
04dc9f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package unify

import (
	"bytes"
	"fmt"
	"html"
	"io"
	"os"
	"os/exec"
	"strings"
)

const maxNodes = 30

type dotEncoder struct {
	w *bytes.Buffer

	idGen    int // Node name generation
	valLimit int // Limit the number of Values in a subgraph

	idp identPrinter
}

func newDotEncoder() *dotEncoder {
	return &dotEncoder{
		w: new(bytes.Buffer),
	}
}

func (enc *dotEncoder) clear() {
	enc.w.Reset()
	enc.idGen = 0
}

func (enc *dotEncoder) writeTo(w io.Writer) {
	fmt.Fprintln(w, "digraph {")
	// Use the "new" ranking algorithm, which lets us put nodes from different
	// clusters in the same rank.
	fmt.Fprintln(w, "newrank=true;")
	fmt.Fprintln(w, "node [shape=box, ordering=out];")

	w.Write(enc.w.Bytes())
	fmt.Fprintln(w, "}")
}

func (enc *dotEncoder) writeSvg(w io.Writer) error {
	cmd := exec.Command("dot", "-Tsvg")
	in, err := cmd.StdinPipe()
	if err != nil {
		return err
	}
	var out bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = os.Stderr
	if err := cmd.Start(); err != nil {
		return err
	}
	enc.writeTo(in)
	in.Close()
	if err := cmd.Wait(); err != nil {
		return err
	}
	// Trim SVG header so the result can be embedded
	//
	// TODO: In Graphviz 10.0.1, we could use -Tsvg_inline.
	svg := out.Bytes()
	if i := bytes.Index(svg, []byte("<svg ")); i >= 0 {
		svg = svg[i:]
	}
	_, err = w.Write(svg)
	return err
}

func (enc *dotEncoder) newID(f string) string {
	id := fmt.Sprintf(f, enc.idGen)
	enc.idGen++
	return id
}

func (enc *dotEncoder) node(label, sublabel string) string {
	id := enc.newID("n%d")
	l := html.EscapeString(label)
	if sublabel != "" {
		l += fmt.Sprintf("<BR ALIGN=\"CENTER\"/><FONT POINT-SIZE=\"10\">%s</FONT>", html.EscapeString(sublabel))
	}
	fmt.Fprintf(enc.w, "%s [label=<%s>];\n", id, l)
	return id
}

func (enc *dotEncoder) edge(from, to string, label string, args ...any) {
	l := fmt.Sprintf(label, args...)
	fmt.Fprintf(enc.w, "%s -> %s [label=%q];\n", from, to, l)
}

func (enc *dotEncoder) valueSubgraph(v *Value) {
	enc.valLimit = maxNodes
	cID := enc.newID("cluster_%d")
	fmt.Fprintf(enc.w, "subgraph %s {\n", cID)
	fmt.Fprintf(enc.w, "style=invis;")
	vID := enc.value(v)
	fmt.Fprintf(enc.w, "}\n")
	// We don't need the IDs right now.
	_, _ = cID, vID
}

func (enc *dotEncoder) value(v *Value) string {
	if enc.valLimit <= 0 {
		id := enc.newID("n%d")
		fmt.Fprintf(enc.w, "%s [label=\"...\", shape=triangle];\n", id)
		return id
	}
	enc.valLimit--

	switch vd := v.Domain.(type) {
	default:
		panic(fmt.Sprintf("unknown domain type %T", vd))

	case nil:
		return enc.node("_|_", "")

	case Top:
		return enc.node("_", "")

		// TODO: Like in YAML, figure out if this is just a sum. In dot, we
		// could say any unentangled variable is a sum, and if it has more than
		// one reference just share the node.

	// case Sum:
	// 	node := enc.node("Sum", "")
	// 	for i, elt := range vd.vs {
	// 		enc.edge(node, enc.value(elt), "%d", i)
	// 		if enc.valLimit <= 0 {
	// 			break
	// 		}
	// 	}
	// 	return node

	case Def:
		node := enc.node("Def", "")
		for k, v := range vd.All() {
			enc.edge(node, enc.value(v), "%s", k)
			if enc.valLimit <= 0 {
				break
			}
		}
		return node

	case Tuple:
		if vd.repeat == nil {
			label := "Tuple"
			node := enc.node(label, "")
			for i, elt := range vd.vs {
				enc.edge(node, enc.value(elt), "%d", i)
				if enc.valLimit <= 0 {
					break
				}
			}
			return node
		} else {
			// TODO
			return enc.node("TODO: Repeat", "")
		}

	case String:
		switch vd.kind {
		case stringExact:
			return enc.node(fmt.Sprintf("%q", vd.exact), "")
		case stringRegex:
			var parts []string
			for _, re := range vd.re {
				parts = append(parts, fmt.Sprintf("%q", re))
			}
			return enc.node(strings.Join(parts, "&"), "")
		}
		panic("bad String kind")

	case Var:
		return enc.node(fmt.Sprintf("Var %s", enc.idp.unique(vd.id)), "")
	}
}

func (enc *dotEncoder) envSubgraph(e envSet) {
	enc.valLimit = maxNodes
	cID := enc.newID("cluster_%d")
	fmt.Fprintf(enc.w, "subgraph %s {\n", cID)
	fmt.Fprintf(enc.w, "style=invis;")
	vID := enc.env(e.root)
	fmt.Fprintf(enc.w, "}\n")
	_, _ = cID, vID
}

func (enc *dotEncoder) env(e *envExpr) string {
	switch e.kind {
	default:
		panic("bad kind")
	case envZero:
		return enc.node("0", "")
	case envUnit:
		return enc.node("1", "")
	case envBinding:
		node := enc.node(fmt.Sprintf("%q :", enc.idp.unique(e.id)), "")
		enc.edge(node, enc.value(e.val), "")
		return node
	case envProduct:
		node := enc.node("⨯", "")
		for _, op := range e.operands {
			enc.edge(node, enc.env(op), "")
		}
		return node
	case envSum:
		node := enc.node("+", "")
		for _, op := range e.operands {
			enc.edge(node, enc.env(op), "")
		}
		return node
	}
}