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
package main

// Graph rendering: Instance -> DOT -> SVG via graphviz.
//
// Server-side graphviz rather than an in-browser layout library: dot's layered
// layout is what produces the look of the Practical Alloy figures, instances are
// small enough that layout cost is irrelevant, and it keeps the browser a dumb
// viewer with no JS build step.

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"sort"
	"strings"
	"time"
)

// edgePalette is Alloy's CLASSIC palette (DotColor MAGIC resolution order),
// assigned to relations in declaration order so each relation gets its own
// colour, as in the GUI.
var edgePalette = []string{
	"#e41a1c", // red
	"#a65628", // brown
	"#ff7f00", // orange
	"#4daf4a", // green
	"#377eb8", // blue
	"#984ea3", // purple
}

// RenderDOT converts one instance to DOT source.
func RenderDOT(inst *Instance, theme *Theme) string {
	if theme == nil {
		theme = DefaultTheme()
	}

	// Relations marked attribute="yes" are folded into node labels instead of
	// being drawn. Do this first so nodes know their attributes before emission.
	//
	// Reset any attributes from a previous render; instances are re-rendered
	// whenever the theme changes.
	for _, a := range inst.Atoms {
		a.Attrs = nil
	}
	// Grouped per relation per node, so a node with (A,B) and (A,C) in F gets a
	// single "F: B, C" line rather than two lines. Matches
	// StaticGraphMaker.edgesAsAttribute.
	for _, rel := range inst.Relations {
		if !theme.edgeAttribute(rel.Name) {
			continue
		}
		if rel.IsSkolem && theme.HideSkolem {
			continue
		}
		perNode := map[*Atom][]string{}
		order := []*Atom{}
		for _, t := range rel.Tuples {
			if len(t) < 2 {
				continue
			}
			src, ok := inst.AtomByName[t[0]]
			if !ok {
				continue
			}
			// Arity > 2 renders the remaining columns joined by "->".
			parts := make([]string, 0, len(t)-1)
			for _, name := range t[1:] {
				if at, ok := inst.AtomByName[name]; ok {
					parts = append(parts, at.Label())
				} else {
					parts = append(parts, name)
				}
			}
			if _, seen := perNode[src]; !seen {
				order = append(order, src)
			}
			perNode[src] = append(perNode[src], strings.Join(parts, "->"))
		}
		for _, src := range order {
			src.Attrs = append(src.Attrs, rel.Name+": "+strings.Join(perNode[src], ", "))
		}
	}

	// Decide which atoms get nodes. An atom is drawn unless its type is hidden
	// by the theme.
	drawn := make(map[string]bool, len(inst.Atoms))
	for _, a := range inst.Atoms {
		if theme.nodeVisible(a.TypeChain) {
			drawn[a.Name] = true
		}
	}

	var b strings.Builder
	b.WriteString("digraph alloy {\n")
	b.WriteString("  graph [rankdir=TB, nodesep=0.35, ranksep=0.5, bgcolor=\"transparent\"];\n")
	b.WriteString("  node  [fontname=\"Helvetica\", fontsize=11, style=filled, penwidth=1];\n")
	b.WriteString("  edge  [fontname=\"Helvetica\", fontsize=10];\n\n")

	// Nodes, in a stable order so the SVG does not churn between renders.
	atoms := append([]*Atom(nil), inst.Atoms...)
	sort.Slice(atoms, func(i, j int) bool {
		if atoms[i].Type != atoms[j].Type {
			return atoms[i].Type < atoms[j].Type
		}
		return atoms[i].Index < atoms[j].Index
	})
	for _, a := range atoms {
		if !drawn[a.Name] {
			continue
		}
		fmt.Fprintf(&b, "  %s [label=%s, shape=%s, fillcolor=%q];\n",
			dotID(a.Name), dotString(a.FullLabel(theme.HideSkolem)),
			theme.nodeShape(a.TypeChain), theme.nodeColor(a.TypeChain))
	}
	b.WriteString("\n")

	// Edges.
	ci := 0
	for _, rel := range inst.Relations {
		if !theme.edgeVisible(rel.Name) || theme.edgeAttribute(rel.Name) {
			continue
		}
		if rel.IsSkolem && theme.HideSkolem {
			continue
		}
		color := edgePalette[ci%len(edgePalette)]
		ci++
		for _, t := range rel.Tuples {
			if len(t) < 2 {
				continue
			}
			src, dst := t[0], t[len(t)-1]
			if !drawn[src] || !drawn[dst] {
				continue
			}
			// Arity > 2: draw first -> last and put the intermediate atoms in
			// the label, matching the GUI ("R [B, C]" for tuple (A,B,C,D)).
			label := rel.Name
			if len(t) > 2 {
				mids := make([]string, 0, len(t)-2)
				for _, m := range t[1 : len(t)-1] {
					if at, ok := inst.AtomByName[m]; ok {
						mids = append(mids, at.Label())
					} else {
						mids = append(mids, m)
					}
				}
				label = fmt.Sprintf("%s [%s]", rel.Name, strings.Join(mids, ", "))
			}
			fmt.Fprintf(&b, "  %s -> %s [label=%s, color=%q, fontcolor=%q];\n",
				dotID(src), dotID(dst), dotString(label), color, color)
		}
	}

	b.WriteString("}\n")
	return b.String()
}

// dotID quotes an atom name for use as a DOT node id. Atom labels contain '$',
// which DOT does not accept unquoted.
func dotID(s string) string { return dotString(s) }

// dotString renders a Go string as a DOT quoted string, escaping quotes,
// backslashes and newlines (\n is meaningful to DOT as a line break).
func dotString(s string) string {
	var b strings.Builder
	b.WriteByte('"')
	for _, r := range s {
		switch r {
		case '"':
			b.WriteString("\\\"")
		case '\\':
			b.WriteString("\\\\")
		case '\n':
			b.WriteString("\\n")
		default:
			b.WriteRune(r)
		}
	}
	b.WriteByte('"')
	return b.String()
}

// RenderSVG pipes DOT source through graphviz.
//
// The timeout guards against a pathological layout wedging the UI; graphviz on
// instances this small is a few milliseconds.
func RenderSVG(ctx context.Context, dot string) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()

	cmd := exec.CommandContext(ctx, "dot", "-Tsvg")
	cmd.Stdin = strings.NewReader(dot)
	var out, errBuf bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &errBuf
	if err := cmd.Run(); err != nil {
		return "", fmt.Errorf("dot -Tsvg: %w: %s", err, strings.TrimSpace(errBuf.String()))
	}
	return stripXMLPreamble(out.String()), nil
}

// stripXMLPreamble removes the XML declaration and DOCTYPE that graphviz emits,
// so the SVG can be inlined directly into an HTML document.
func stripXMLPreamble(svg string) string {
	if i := strings.Index(svg, "<svg"); i > 0 {
		return svg[i:]
	}
	return svg
}