File size: 6,850 Bytes
13c2bf6 | 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | // Copyright 2022 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 dag implements a language for expressing directed acyclic
// graphs.
//
// The general syntax of a rule is:
//
// a, b < c, d;
//
// which means c and d come after a and b in the partial order
// (that is, there are edges from c and d to a and b),
// but doesn't provide a relative order between a vs b or c vs d.
//
// The rules can chain together, as in:
//
// e < f, g < h;
//
// which is equivalent to
//
// e < f, g;
// f, g < h;
//
// Except for the special bottom element "NONE", each name
// must appear exactly once on the right-hand side of any rule.
// That rule serves as the definition of the allowed successor
// for that name. The definition must appear before any uses
// of the name on the left-hand side of a rule. (That is, the
// rules themselves must be ordered according to the partial
// order, for easier reading by people.)
//
// Negative assertions double-check the partial order:
//
// i !< j
//
// means that it must NOT be the case that i < j.
// Negative assertions may appear anywhere in the rules,
// even before i and j have been defined.
//
// Comments begin with #.
package dag
import (
"cmp"
"fmt"
"slices"
"strings"
)
type Graph struct {
Nodes []string
byLabel map[string]int
edges map[string]map[string]bool
}
func newGraph() *Graph {
return &Graph{byLabel: map[string]int{}, edges: map[string]map[string]bool{}}
}
func (g *Graph) addNode(label string) bool {
if _, ok := g.byLabel[label]; ok {
return false
}
g.byLabel[label] = len(g.Nodes)
g.Nodes = append(g.Nodes, label)
g.edges[label] = map[string]bool{}
return true
}
func (g *Graph) AddEdge(from, to string) {
g.edges[from][to] = true
}
func (g *Graph) DelEdge(from, to string) {
delete(g.edges[from], to)
}
func (g *Graph) HasEdge(from, to string) bool {
return g.edges[from] != nil && g.edges[from][to]
}
func (g *Graph) Edges(from string) []string {
edges := make([]string, 0, 16)
for k := range g.edges[from] {
edges = append(edges, k)
}
slices.SortFunc(edges, func(a, b string) int {
return cmp.Compare(g.byLabel[a], g.byLabel[b])
})
return edges
}
// Parse parses the DAG language and returns the transitive closure of
// the described graph. In the returned graph, there is an edge from "b"
// to "a" if b < a (or a > b) in the partial order.
func Parse(dag string) (*Graph, error) {
g := newGraph()
disallowed := []rule{}
rules, err := parseRules(dag)
if err != nil {
return nil, err
}
// TODO: Add line numbers to errors.
var errors []string
errorf := func(format string, a ...any) {
errors = append(errors, fmt.Sprintf(format, a...))
}
for _, r := range rules {
if r.op == "!<" {
disallowed = append(disallowed, r)
continue
}
for _, def := range r.def {
if def == "NONE" {
errorf("NONE cannot be a predecessor")
continue
}
if !g.addNode(def) {
errorf("multiple definitions for %s", def)
}
for _, less := range r.less {
if less == "NONE" {
continue
}
if _, ok := g.byLabel[less]; !ok {
errorf("use of %s before its definition", less)
} else {
g.AddEdge(def, less)
}
}
}
}
// Check for missing definition.
for _, tos := range g.edges {
for to := range tos {
if g.edges[to] == nil {
errorf("missing definition for %s", to)
}
}
}
// Complete transitive closure.
for _, k := range g.Nodes {
for _, i := range g.Nodes {
for _, j := range g.Nodes {
if i != k && k != j && g.HasEdge(i, k) && g.HasEdge(k, j) {
if i == j {
// Can only happen along with a "use of X before deps" error above,
// but this error is more specific - it makes clear that reordering the
// rules will not be enough to fix the problem.
errorf("graph cycle: %s < %s < %s", j, k, i)
}
g.AddEdge(i, j)
}
}
}
}
// Check negative assertions against completed allowed graph.
for _, bad := range disallowed {
for _, less := range bad.less {
for _, def := range bad.def {
if g.HasEdge(def, less) {
errorf("graph edge assertion failed: %s !< %s", less, def)
}
}
}
}
if len(errors) > 0 {
return nil, fmt.Errorf("%s", strings.Join(errors, "\n"))
}
return g, nil
}
// A rule is a line in the DAG language where "less < def" or "less !< def".
type rule struct {
less []string
op string // Either "<" or "!<"
def []string
}
type syntaxError string
func (e syntaxError) Error() string {
return string(e)
}
// parseRules parses the rules of a DAG.
func parseRules(rules string) (out []rule, err error) {
defer func() {
e := recover()
switch e := e.(type) {
case nil:
return
case syntaxError:
err = e
default:
panic(e)
}
}()
p := &rulesParser{lineno: 1, text: rules}
var prev []string
var op string
for {
list, tok := p.nextList()
if tok == "" {
if prev == nil {
break
}
p.syntaxError("unexpected EOF")
}
if prev != nil {
out = append(out, rule{prev, op, list})
}
prev = list
if tok == ";" {
prev = nil
op = ""
continue
}
if tok != "<" && tok != "!<" {
p.syntaxError("missing <")
}
op = tok
}
return out, err
}
// A rulesParser parses the depsRules syntax described above.
type rulesParser struct {
lineno int
lastWord string
text string
}
// syntaxError reports a parsing error.
func (p *rulesParser) syntaxError(msg string) {
panic(syntaxError(fmt.Sprintf("parsing graph: line %d: syntax error: %s near %s", p.lineno, msg, p.lastWord)))
}
// nextList parses and returns a comma-separated list of names.
func (p *rulesParser) nextList() (list []string, token string) {
for {
tok := p.nextToken()
switch tok {
case "":
if len(list) == 0 {
return nil, ""
}
fallthrough
case ",", "<", "!<", ";":
p.syntaxError("bad list syntax")
}
list = append(list, tok)
tok = p.nextToken()
if tok != "," {
return list, tok
}
}
}
// nextToken returns the next token in the deps rules,
// one of ";" "," "<" "!<" or a name.
func (p *rulesParser) nextToken() string {
for {
if p.text == "" {
return ""
}
switch p.text[0] {
case ';', ',', '<':
t := p.text[:1]
p.text = p.text[1:]
return t
case '!':
if len(p.text) < 2 || p.text[1] != '<' {
p.syntaxError("unexpected token !")
}
p.text = p.text[2:]
return "!<"
case '#':
i := strings.Index(p.text, "\n")
if i < 0 {
i = len(p.text)
}
p.text = p.text[i:]
continue
case '\n':
p.lineno++
fallthrough
case ' ', '\t':
p.text = p.text[1:]
continue
default:
i := strings.IndexAny(p.text, "!;,<#\n \t")
if i < 0 {
i = len(p.text)
}
t := p.text[:i]
p.text = p.text[i:]
p.lastWord = t
return t
}
}
}
|