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  	"cmp"
    12  	"container/heap"
    13  	"fmt"
    14  	. "internal/types/errors"
    15  	"slices"
    16  )
    17  
    18  // initOrder computes the Info.InitOrder for package variables.
    19  func (check *Checker) initOrder() {
    20  	// An InitOrder may already have been computed if a package is
    21  	// built from several calls to (*Checker).Files. Clear it.
    22  	check.Info.InitOrder = check.Info.InitOrder[:0]
    23  
    24  	// Compute the object dependency graph and initialize
    25  	// a priority queue with the list of graph nodes.
    26  	pq := nodeQueue(dependencyGraph(check.objMap))
    27  	heap.Init(&pq)
    28  
    29  	const debug = false
    30  	if debug {
    31  		fmt.Printf("Computing initialization order for %s\n\n", check.pkg)
    32  		fmt.Println("Object dependency graph:")
    33  		for obj, d := range check.objMap {
    34  			// only print objects that may appear in the dependency graph
    35  			if obj, _ := obj.(dependency); obj != nil {
    36  				if len(d.deps) > 0 {
    37  					fmt.Printf("\t%s depends on\n", obj.Name())
    38  					for dep := range d.deps {
    39  						fmt.Printf("\t\t%s\n", dep.Name())
    40  					}
    41  				} else {
    42  					fmt.Printf("\t%s has no dependencies\n", obj.Name())
    43  				}
    44  			}
    45  		}
    46  		fmt.Println()
    47  
    48  		fmt.Println("Transposed object dependency graph (functions eliminated):")
    49  		for _, n := range pq {
    50  			fmt.Printf("\t%s depends on %d nodes\n", n.obj.Name(), n.ndeps)
    51  			for p := range n.pred {
    52  				fmt.Printf("\t\t%s is dependent\n", p.obj.Name())
    53  			}
    54  		}
    55  		fmt.Println()
    56  
    57  		fmt.Println("Processing nodes:")
    58  	}
    59  
    60  	// Determine initialization order by removing the highest priority node
    61  	// (the one with the fewest dependencies) and its edges from the graph,
    62  	// repeatedly, until there are no nodes left.
    63  	// In a valid Go program, those nodes always have zero dependencies (after
    64  	// removing all incoming dependencies), otherwise there are initialization
    65  	// cycles.
    66  	emitted := make(map[*declInfo]bool)
    67  	for len(pq) > 0 {
    68  		// get the next node
    69  		n := heap.Pop(&pq).(*graphNode)
    70  
    71  		if debug {
    72  			fmt.Printf("\t%s (src pos %d) depends on %d nodes now\n",
    73  				n.obj.Name(), n.obj.order(), n.ndeps)
    74  		}
    75  
    76  		// if n still depends on other nodes, we have a cycle
    77  		if n.ndeps > 0 {
    78  			cycle := findPath(check.objMap, n.obj, n.obj, make(map[Object]bool))
    79  			// If n.obj is not part of the cycle (e.g., n.obj->b->c->d->c),
    80  			// cycle will be nil. Don't report anything in that case since
    81  			// the cycle is reported when the algorithm gets to an object
    82  			// in the cycle.
    83  			// Furthermore, once an object in the cycle is encountered,
    84  			// the cycle will be broken (dependency count will be reduced
    85  			// below), and so the remaining nodes in the cycle don't trigger
    86  			// another error (unless they are part of multiple cycles).
    87  			if cycle != nil {
    88  				check.reportCycle(cycle)
    89  			}
    90  			// Ok to continue, but the variable initialization order
    91  			// will be incorrect at this point since it assumes no
    92  			// cycle errors.
    93  		}
    94  
    95  		// reduce dependency count of all dependent nodes
    96  		// and update priority queue
    97  		for p := range n.pred {
    98  			p.ndeps--
    99  			heap.Fix(&pq, p.index)
   100  		}
   101  
   102  		// record the init order for variables with initializers only
   103  		v, _ := n.obj.(*Var)
   104  		info := check.objMap[v]
   105  		if v == nil || !info.hasInitializer() {
   106  			continue
   107  		}
   108  
   109  		// n:1 variable declarations such as: a, b = f()
   110  		// introduce a node for each lhs variable (here: a, b);
   111  		// but they all have the same initializer - emit only
   112  		// one, for the first variable seen
   113  		if emitted[info] {
   114  			continue // initializer already emitted, if any
   115  		}
   116  		emitted[info] = true
   117  
   118  		infoLhs := info.lhs // possibly nil (see declInfo.lhs field comment)
   119  		if infoLhs == nil {
   120  			infoLhs = []*Var{v}
   121  		}
   122  		init := &Initializer{infoLhs, info.init}
   123  		check.Info.InitOrder = append(check.Info.InitOrder, init)
   124  	}
   125  
   126  	if debug {
   127  		fmt.Println()
   128  		fmt.Println("Initialization order:")
   129  		for _, init := range check.Info.InitOrder {
   130  			fmt.Printf("\t%s\n", init)
   131  		}
   132  		fmt.Println()
   133  	}
   134  }
   135  
   136  // findPath returns the (reversed) list of objects []Object{to, ... from}
   137  // such that there is a path of object dependencies from 'from' to 'to'.
   138  // If there is no such path, the result is nil.
   139  func findPath(objMap map[Object]*declInfo, from, to Object, seen map[Object]bool) []Object {
   140  	if seen[from] {
   141  		return nil
   142  	}
   143  	seen[from] = true
   144  
   145  	for d := range objMap[from].deps {
   146  		if d == to {
   147  			return []Object{d}
   148  		}
   149  		if P := findPath(objMap, d, to, seen); P != nil {
   150  			return append(P, d)
   151  		}
   152  	}
   153  
   154  	return nil
   155  }
   156  
   157  // reportCycle reports an error for the given cycle.
   158  func (check *Checker) reportCycle(cycle []Object) {
   159  	obj := cycle[0]
   160  
   161  	// report a more concise error for self references
   162  	if len(cycle) == 1 {
   163  		check.errorf(obj, InvalidInitCycle, "initialization cycle: %s refers to itself", obj.Name())
   164  		return
   165  	}
   166  
   167  	err := check.newError(InvalidInitCycle)
   168  	err.addf(obj, "initialization cycle for %s", obj.Name())
   169  	// "cycle[i] refers to cycle[j]" for (i,j) = (0,n-1), (n-1,n-2), ..., (1,0) for len(cycle) = n.
   170  	for j := len(cycle) - 1; j >= 0; j-- {
   171  		next := cycle[j]
   172  		err.addf(obj, "%s refers to %s", obj.Name(), next.Name())
   173  		obj = next
   174  	}
   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  	slices.SortFunc(funcG, func(a, b *graphNode) int {
   264  		return cmp.Compare(a.cost(), b.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