Source file src/go/types/initorder.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/initorder.go
     3  
     4  // Copyright 2014 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  package types
     9  
    10  import (
    11  	"container/heap"
    12  	"fmt"
    13  	. "internal/types/errors"
    14  	"sort"
    15  )
    16  
    17  // initOrder computes the Info.InitOrder for package variables.
    18  func (check *Checker) initOrder() {
    19  	// An InitOrder may already have been computed if a package is
    20  	// built from several calls to (*Checker).Files. Clear it.
    21  	check.Info.InitOrder = check.Info.InitOrder[:0]
    22  
    23  	// Compute the object dependency graph and initialize
    24  	// a priority queue with the list of graph nodes.
    25  	pq := nodeQueue(dependencyGraph(check.objMap))
    26  	heap.Init(&pq)
    27  
    28  	const debug = false
    29  	if debug {
    30  		fmt.Printf("Computing initialization order for %s\n\n", check.pkg)
    31  		fmt.Println("Object dependency graph:")
    32  		for obj, d := range check.objMap {
    33  			// only print objects that may appear in the dependency graph
    34  			if obj, _ := obj.(dependency); obj != nil {
    35  				if len(d.deps) > 0 {
    36  					fmt.Printf("\t%s depends on\n", obj.Name())
    37  					for dep := range d.deps {
    38  						fmt.Printf("\t\t%s\n", dep.Name())
    39  					}
    40  				} else {
    41  					fmt.Printf("\t%s has no dependencies\n", obj.Name())
    42  				}
    43  			}
    44  		}
    45  		fmt.Println()
    46  
    47  		fmt.Println("Transposed object dependency graph (functions eliminated):")
    48  		for _, n := range pq {
    49  			fmt.Printf("\t%s depends on %d nodes\n", n.obj.Name(), n.ndeps)
    50  			for p := range n.pred {
    51  				fmt.Printf("\t\t%s is dependent\n", p.obj.Name())
    52  			}
    53  		}
    54  		fmt.Println()
    55  
    56  		fmt.Println("Processing nodes:")
    57  	}
    58  
    59  	// Determine initialization order by removing the highest priority node
    60  	// (the one with the fewest dependencies) and its edges from the graph,
    61  	// repeatedly, until there are no nodes left.
    62  	// In a valid Go program, those nodes always have zero dependencies (after
    63  	// removing all incoming dependencies), otherwise there are initialization
    64  	// cycles.
    65  	emitted := make(map[*declInfo]bool)
    66  	for len(pq) > 0 {
    67  		// get the next node
    68  		n := heap.Pop(&pq).(*graphNode)
    69  
    70  		if debug {
    71  			fmt.Printf("\t%s (src pos %d) depends on %d nodes now\n",
    72  				n.obj.Name(), n.obj.order(), n.ndeps)
    73  		}
    74  
    75  		// if n still depends on other nodes, we have a cycle
    76  		if n.ndeps > 0 {
    77  			cycle := findPath(check.objMap, n.obj, n.obj, make(map[Object]bool))
    78  			// If n.obj is not part of the cycle (e.g., n.obj->b->c->d->c),
    79  			// cycle will be nil. Don't report anything in that case since
    80  			// the cycle is reported when the algorithm gets to an object
    81  			// in the cycle.
    82  			// Furthermore, once an object in the cycle is encountered,
    83  			// the cycle will be broken (dependency count will be reduced
    84  			// below), and so the remaining nodes in the cycle don't trigger
    85  			// another error (unless they are part of multiple cycles).
    86  			if cycle != nil {
    87  				check.reportCycle(cycle)
    88  			}
    89  			// Ok to continue, but the variable initialization order
    90  			// will be incorrect at this point since it assumes no
    91  			// cycle errors.
    92  		}
    93  
    94  		// reduce dependency count of all dependent nodes
    95  		// and update priority queue
    96  		for p := range n.pred {
    97  			p.ndeps--
    98  			heap.Fix(&pq, p.index)
    99  		}
   100  
   101  		// record the init order for variables with initializers only
   102  		v, _ := n.obj.(*Var)
   103  		info := check.objMap[v]
   104  		if v == nil || !info.hasInitializer() {
   105  			continue
   106  		}
   107  
   108  		// n:1 variable declarations such as: a, b = f()
   109  		// introduce a node for each lhs variable (here: a, b);
   110  		// but they all have the same initializer - emit only
   111  		// one, for the first variable seen
   112  		if emitted[info] {
   113  			continue // initializer already emitted, if any
   114  		}
   115  		emitted[info] = true
   116  
   117  		infoLhs := info.lhs // possibly nil (see declInfo.lhs field comment)
   118  		if infoLhs == nil {
   119  			infoLhs = []*Var{v}
   120  		}
   121  		init := &Initializer{infoLhs, info.init}
   122  		check.Info.InitOrder = append(check.Info.InitOrder, init)
   123  	}
   124  
   125  	if debug {
   126  		fmt.Println()
   127  		fmt.Println("Initialization order:")
   128  		for _, init := range check.Info.InitOrder {
   129  			fmt.Printf("\t%s\n", init)
   130  		}
   131  		fmt.Println()
   132  	}
   133  }
   134  
   135  // findPath returns the (reversed) list of objects []Object{to, ... from}
   136  // such that there is a path of object dependencies from 'from' to 'to'.
   137  // If there is no such path, the result is nil.
   138  func findPath(objMap map[Object]*declInfo, from, to Object, seen map[Object]bool) []Object {
   139  	if seen[from] {
   140  		return nil
   141  	}
   142  	seen[from] = true
   143  
   144  	for d := range objMap[from].deps {
   145  		if d == to {
   146  			return []Object{d}
   147  		}
   148  		if P := findPath(objMap, d, to, seen); P != nil {
   149  			return append(P, d)
   150  		}
   151  	}
   152  
   153  	return nil
   154  }
   155  
   156  // reportCycle reports an error for the given cycle.
   157  func (check *Checker) reportCycle(cycle []Object) {
   158  	obj := cycle[0]
   159  
   160  	// report a more concise error for self references
   161  	if len(cycle) == 1 {
   162  		check.errorf(obj, InvalidInitCycle, "initialization cycle: %s refers to itself", obj.Name())
   163  		return
   164  	}
   165  
   166  	err := check.newError(InvalidInitCycle)
   167  	err.addf(obj, "initialization cycle for %s", obj.Name())
   168  	// subtle loop: print cycle[i] for i = 0, n-1, n-2, ... 1 for len(cycle) = n
   169  	for i := len(cycle) - 1; i >= 0; i-- {
   170  		err.addf(obj, "%s refers to", obj.Name())
   171  		obj = cycle[i]
   172  	}
   173  	// print cycle[0] again to close the cycle
   174  	err.addf(obj, "%s", obj.Name())
   175  	err.report()
   176  }
   177  
   178  // ----------------------------------------------------------------------------
   179  // Object dependency graph
   180  
   181  // A dependency is an object that may be a dependency in an initialization
   182  // expression. Only constants, variables, and functions can be dependencies.
   183  // Constants are here because constant expression cycles are reported during
   184  // initialization order computation.
   185  type dependency interface {
   186  	Object
   187  	isDependency()
   188  }
   189  
   190  // A graphNode represents a node in the object dependency graph.
   191  // Each node p in n.pred represents an edge p->n, and each node
   192  // s in n.succ represents an edge n->s; with a->b indicating that
   193  // a depends on b.
   194  type graphNode struct {
   195  	obj        dependency // object represented by this node
   196  	pred, succ nodeSet    // consumers and dependencies of this node (lazily initialized)
   197  	index      int        // node index in graph slice/priority queue
   198  	ndeps      int        // number of outstanding dependencies before this object can be initialized
   199  }
   200  
   201  // cost returns the cost of removing this node, which involves copying each
   202  // predecessor to each successor (and vice-versa).
   203  func (n *graphNode) cost() int {
   204  	return len(n.pred) * len(n.succ)
   205  }
   206  
   207  type nodeSet map[*graphNode]bool
   208  
   209  func (s *nodeSet) add(p *graphNode) {
   210  	if *s == nil {
   211  		*s = make(nodeSet)
   212  	}
   213  	(*s)[p] = true
   214  }
   215  
   216  // dependencyGraph computes the object dependency graph from the given objMap,
   217  // with any function nodes removed. The resulting graph contains only constants
   218  // and variables.
   219  func dependencyGraph(objMap map[Object]*declInfo) []*graphNode {
   220  	// M is the dependency (Object) -> graphNode mapping
   221  	M := make(map[dependency]*graphNode)
   222  	for obj := range objMap {
   223  		// only consider nodes that may be an initialization dependency
   224  		if obj, _ := obj.(dependency); obj != nil {
   225  			M[obj] = &graphNode{obj: obj}
   226  		}
   227  	}
   228  
   229  	// compute edges for graph M
   230  	// (We need to include all nodes, even isolated ones, because they still need
   231  	// to be scheduled for initialization in correct order relative to other nodes.)
   232  	for obj, n := range M {
   233  		// for each dependency obj -> d (= deps[i]), create graph edges n->s and s->n
   234  		for d := range objMap[obj].deps {
   235  			// only consider nodes that may be an initialization dependency
   236  			if d, _ := d.(dependency); d != nil {
   237  				d := M[d]
   238  				n.succ.add(d)
   239  				d.pred.add(n)
   240  			}
   241  		}
   242  	}
   243  
   244  	var G, funcG []*graphNode // separate non-functions and functions
   245  	for _, n := range M {
   246  		if _, ok := n.obj.(*Func); ok {
   247  			funcG = append(funcG, n)
   248  		} else {
   249  			G = append(G, n)
   250  		}
   251  	}
   252  
   253  	// remove function nodes and collect remaining graph nodes in G
   254  	// (Mutually recursive functions may introduce cycles among themselves
   255  	// which are permitted. Yet such cycles may incorrectly inflate the dependency
   256  	// count for variables which in turn may not get scheduled for initialization
   257  	// in correct order.)
   258  	//
   259  	// Note that because we recursively copy predecessors and successors
   260  	// throughout the function graph, the cost of removing a function at
   261  	// position X is proportional to cost * (len(funcG)-X). Therefore, we should
   262  	// remove high-cost functions last.
   263  	sort.Slice(funcG, func(i, j int) bool {
   264  		return funcG[i].cost() < funcG[j].cost()
   265  	})
   266  	for _, n := range funcG {
   267  		// connect each predecessor p of n with each successor s
   268  		// and drop the function node (don't collect it in G)
   269  		for p := range n.pred {
   270  			// ignore self-cycles
   271  			if p != n {
   272  				// Each successor s of n becomes a successor of p, and
   273  				// each predecessor p of n becomes a predecessor of s.
   274  				for s := range n.succ {
   275  					// ignore self-cycles
   276  					if s != n {
   277  						p.succ.add(s)
   278  						s.pred.add(p)
   279  					}
   280  				}
   281  				delete(p.succ, n) // remove edge to n
   282  			}
   283  		}
   284  		for s := range n.succ {
   285  			delete(s.pred, n) // remove edge to n
   286  		}
   287  	}
   288  
   289  	// fill in index and ndeps fields
   290  	for i, n := range G {
   291  		n.index = i
   292  		n.ndeps = len(n.succ)
   293  	}
   294  
   295  	return G
   296  }
   297  
   298  // ----------------------------------------------------------------------------
   299  // Priority queue
   300  
   301  // nodeQueue implements the container/heap interface;
   302  // a nodeQueue may be used as a priority queue.
   303  type nodeQueue []*graphNode
   304  
   305  func (a nodeQueue) Len() int { return len(a) }
   306  
   307  func (a nodeQueue) Swap(i, j int) {
   308  	x, y := a[i], a[j]
   309  	a[i], a[j] = y, x
   310  	x.index, y.index = j, i
   311  }
   312  
   313  func (a nodeQueue) Less(i, j int) bool {
   314  	x, y := a[i], a[j]
   315  
   316  	// Prioritize all constants before non-constants. See go.dev/issue/66575/.
   317  	_, xConst := x.obj.(*Const)
   318  	_, yConst := y.obj.(*Const)
   319  	if xConst != yConst {
   320  		return xConst
   321  	}
   322  
   323  	// nodes are prioritized by number of incoming dependencies (1st key)
   324  	// and source order (2nd key)
   325  	return x.ndeps < y.ndeps || x.ndeps == y.ndeps && x.obj.order() < y.obj.order()
   326  }
   327  
   328  func (a *nodeQueue) Push(x any) {
   329  	panic("unreachable")
   330  }
   331  
   332  func (a *nodeQueue) Pop() any {
   333  	n := len(*a)
   334  	x := (*a)[n-1]
   335  	x.index = -1 // for safety
   336  	*a = (*a)[:n-1]
   337  	return x
   338  }
   339  

View as plain text