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 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
|
// Copyright 2024 CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package toposort
import (
"cmp"
"math"
"slices"
"cuelang.org/go/internal/core/adt"
)
const (
NodeUnsorted = -1
NodeInCurrentScc = -2
)
type Graph struct {
nodes Nodes
}
type Node struct {
Feature adt.Feature
Outgoing Nodes
Incoming Nodes
structMeta *structMeta
// temporary state for calculating the Strongly Connected
// Components of a graph.
sccNodeState *sccNodeState
// temporary state for calculating the Elementary Cycles of a
// graph.
ecNodeState *ecNodeState
position int
}
func (n *Node) IsSorted() bool {
return n.position >= 0
}
// SafeName returns a string useful for debugging, regardless of the
// type of the feature. So for IntLabels, you'll get back `1`, `10`
// etc; for identifiers, you may get back a string with quotes in it,
// eg `"runs-on"`. So this is not useful for comparisons, but it is
// useful (and safe) for debugging.
func (n *Node) SafeName(index adt.StringIndexer) string {
return n.Feature.SelectorString(index)
}
type Nodes []*Node
func (nodes Nodes) Features() []adt.Feature {
features := make([]adt.Feature, len(nodes))
for i, node := range nodes {
features[i] = node.Feature
}
return features
}
type edge struct {
from adt.Feature
to adt.Feature
}
type GraphBuilder struct {
allowEdges bool
edgesSet map[edge]struct{}
nodesByFeature map[adt.Feature]*Node
}
// NewGraphBuilder is the constructor for GraphBuilder.
//
// If you disallow edges, then nodes can still be added to the graph,
// and the [GraphBuilder.AddEdge] method will not error, but edges
// will never be added between nodes. This has the effect that
// topological ordering is not possible.
func NewGraphBuilder(allowEdges bool) *GraphBuilder {
return &GraphBuilder{
allowEdges: allowEdges,
edgesSet: make(map[edge]struct{}),
nodesByFeature: make(map[adt.Feature]*Node),
}
}
// Adds an edge between the two features. Nodes for the features will
// be created if they don't already exist. This method is idempotent:
// multiple calls with the same arguments will not create multiple
// edges, nor error.
func (builder *GraphBuilder) AddEdge(from, to adt.Feature) {
if !builder.allowEdges {
builder.EnsureNode(from)
builder.EnsureNode(to)
return
}
edge := edge{from: from, to: to}
if _, found := builder.edgesSet[edge]; found {
return
}
builder.edgesSet[edge] = struct{}{}
fromNode := builder.EnsureNode(from)
toNode := builder.EnsureNode(to)
fromNode.Outgoing = append(fromNode.Outgoing, toNode)
toNode.Incoming = append(toNode.Incoming, fromNode)
}
// Ensure that a node for this feature exists. This is necessary for
// features that are not necessarily connected to any other feature.
func (builder *GraphBuilder) EnsureNode(feature adt.Feature) *Node {
node, found := builder.nodesByFeature[feature]
if !found {
node = &Node{Feature: feature, position: NodeUnsorted}
builder.nodesByFeature[feature] = node
}
return node
}
func (builder *GraphBuilder) Build() *Graph {
nodesByFeature := builder.nodesByFeature
nodes := make(Nodes, 0, len(nodesByFeature))
for _, node := range nodesByFeature {
nodes = append(nodes, node)
}
return &Graph{nodes: nodes}
}
type indexComparison struct{ adt.StringIndexer }
func (index *indexComparison) compareNodeByName(a, b *Node) int {
aFeature, bFeature := a.Feature, b.Feature
aIsInt, bIsInt := aFeature.Typ() == adt.IntLabel, bFeature.Typ() == adt.IntLabel
switch {
case aIsInt && bIsInt:
return cmp.Compare(aFeature.Index(), bFeature.Index())
case aIsInt:
return -1
case bIsInt:
return 1
default:
return cmp.Compare(aFeature.RawString(index), bFeature.RawString(index))
}
}
func (index *indexComparison) compareCyclesByNames(a, b *Cycle) int {
return slices.CompareFunc(a.Nodes, b.Nodes, index.compareNodeByName)
}
func (index *indexComparison) compareComponentsByNodes(a, b *StronglyConnectedComponent) int {
return slices.CompareFunc(a.Nodes, b.Nodes, index.compareNodeByName)
}
func chooseCycleEntryNode(cycle *Cycle) (entryNode *Node, enabledSince, brokenEdgeCount int) {
enabledSince = math.MaxInt
for _, cycleNode := range cycle.Nodes {
if cycleNode.IsSorted() {
// this node is already in the sorted result
continue
}
NextNodeIncoming:
for _, incoming := range cycleNode.Incoming {
position := incoming.position
if position < 0 {
// this predecessor node has not yet been added to the sorted
// result.
for _, cycleNode1 := range cycle.Nodes {
// ignore this predecessor node if it is part of this cycle.
if cycleNode1 == incoming {
continue NextNodeIncoming
}
}
brokenEdgeCount++
continue NextNodeIncoming
}
// this predecessor node must already be in the sorted output.
if position < enabledSince {
enabledSince = position
entryNode = cycleNode
}
}
}
return entryNode, enabledSince, brokenEdgeCount
}
func chooseCycle(indexCmp *indexComparison, unusedCycles []*Cycle) *Cycle {
chosenCycleIdx := -1
chosenCycleBrokenEdgeCount := math.MaxInt
chosenCycleEnabledSince := math.MaxInt
var chosenCycleEntryNode *Node
for i, cycle := range unusedCycles {
if cycle == nil {
continue
}
debug("cycle %d: %v\n", i, cycle)
entryNode, enabledSince, brokenEdgeCount := chooseCycleEntryNode(cycle)
if entryNode == nil {
entryNode = slices.MinFunc(
cycle.Nodes, indexCmp.compareNodeByName)
}
debug("cycle %v; edgeCount %v; enabledSince %v; entryNode %v\n",
cycle, brokenEdgeCount, enabledSince,
entryNode.SafeName(indexCmp))
cycleIsBetter := chosenCycleIdx == -1
// this is written out long-form for ease of readability
switch {
case cycleIsBetter:
// noop
case brokenEdgeCount < chosenCycleBrokenEdgeCount:
cycleIsBetter = true
case brokenEdgeCount > chosenCycleBrokenEdgeCount:
// noop - only continue if ==
case enabledSince < chosenCycleEnabledSince:
cycleIsBetter = true
case enabledSince > chosenCycleEnabledSince:
// noop - only continue if ==
case indexCmp.compareNodeByName(entryNode, chosenCycleEntryNode) < 0:
cycleIsBetter = true
case entryNode == chosenCycleEntryNode:
cycleIsBetter =
indexCmp.compareCyclesByNames(cycle, unusedCycles[chosenCycleIdx]) < 0
}
if cycleIsBetter {
chosenCycleIdx = i
chosenCycleBrokenEdgeCount = brokenEdgeCount
chosenCycleEnabledSince = enabledSince
chosenCycleEntryNode = entryNode
}
}
if chosenCycleEntryNode == nil {
return nil
}
debug("Chose cycle: %v; entering at node: %s\n",
unusedCycles[chosenCycleIdx], chosenCycleEntryNode.SafeName(indexCmp))
cycle := unusedCycles[chosenCycleIdx]
unusedCycles[chosenCycleIdx] = nil
cycle.RotateToStartAt(chosenCycleEntryNode)
return cycle
}
// Sort the features of the graph into a single slice.
//
// As far as possible, a topological sort is used.
//
// Whenever there is choice as to which feature should occur next, a
// lexicographical comparison is done, and minimum feature chosen.
//
// Whenever progress cannot be made due to needing to enter into
// cycles, the cycle to enter into, and the node of that cycle with
// which to start, is selected based on:
//
// 1. minimising the number of incoming edges that are violated
// 2. chosing a node which was reachable as early as possible
// 3. chosing a node with a smaller feature name (lexicographical)
func (graph *Graph) Sort(index adt.StringIndexer) []adt.Feature {
indexCmp := &indexComparison{index}
nodesSorted := make(Nodes, 0, len(graph.nodes))
scc := graph.StronglyConnectedComponents()
var sccReady []*StronglyConnectedComponent
for _, component := range scc {
component.visited = false
slices.SortFunc(component.Nodes, indexCmp.compareNodeByName)
if len(component.Incoming) == 0 {
sccReady = append(sccReady, component)
}
}
slices.SortFunc(sccReady, indexCmp.compareComponentsByNodes)
sccVisitedCount := 0
for sccVisitedCount != len(scc) {
sccCurrent := sccReady[0]
sccReady = sccReady[1:]
if sccCurrent.visited {
continue
}
sccCurrent.visited = true
sccVisitedCount++
debug("scc current: %p %v\n", sccCurrent, sccCurrent)
var cyclesCurrent []*Cycle
var nodesReady Nodes
NextNode:
for _, node := range sccCurrent.Nodes {
node.position = NodeInCurrentScc
for _, required := range node.Incoming {
if !required.IsSorted() {
continue NextNode
}
}
nodesReady = append(nodesReady, node)
}
slices.SortFunc(nodesReady, indexCmp.compareNodeByName)
requiredLen := len(nodesSorted) + len(sccCurrent.Nodes)
for requiredLen != len(nodesSorted) {
if len(nodesReady) == 0 {
debug("Stuck after: %v\n", nodesSorted)
if cyclesCurrent == nil {
cyclesCurrent = sccCurrent.ElementaryCycles()
debug("cycles current: %v\n", cyclesCurrent)
}
cycle := chooseCycle(indexCmp, cyclesCurrent)
if cycle == nil {
panic("No cycle found.")
}
nodesSorted, nodesReady = appendNodes(
indexCmp, nodesSorted, cycle.Nodes, nodesReady)
} else {
nodesSorted, nodesReady = appendNodes(
indexCmp, nodesSorted, nodesReady[:1], nodesReady[1:])
}
}
sccReadyNeedsSorting := false
SccNextOutgoing:
for _, next := range sccCurrent.Outgoing {
for _, required := range next.Incoming {
if !required.visited {
continue SccNextOutgoing
}
}
sccReady = append(sccReady, next)
sccReadyNeedsSorting = true
}
if sccReadyNeedsSorting {
slices.SortFunc(sccReady, indexCmp.compareComponentsByNodes)
}
}
return nodesSorted.Features()
}
func appendNodes(indexCmp *indexComparison, nodesSorted, nodesReady, nodesEnabled Nodes) (nodesSortedOut, nodesEnabledOut Nodes) {
nodesReadyNeedsSorting := false
for _, node := range nodesReady {
if node.IsSorted() {
continue
}
node.position = len(nodesSorted)
nodesSorted = append(nodesSorted, node)
NextOutgoing:
for _, next := range node.Outgoing {
if next.position != NodeInCurrentScc {
continue
}
for _, required := range next.Incoming {
if !required.IsSorted() {
continue NextOutgoing
}
}
debug("After %v, found new ready: %s\n",
nodesSorted, next.SafeName(indexCmp))
nodesEnabled = append(nodesEnabled, next)
nodesReadyNeedsSorting = true
}
}
if nodesReadyNeedsSorting {
slices.SortFunc(nodesEnabled, indexCmp.compareNodeByName)
}
return nodesSorted, nodesEnabled
}
func debug(formatting string, args ...any) {
// fmt.Printf(formatting, args...)
}
|