generic_forward_field.mx raw

   1  // A field of an instantiated generic keeps its type when the generic it names
   2  // is declared LATER in the same file.
   3  //
   4  // `mapping[K,V]` is declared above `entry[K,V]`, which its slice field names.
   5  // The recorded defect (the work log, item 3b) was that the forward
   6  // reference left the field's element a bare type parameter: instantiating
   7  // mapping[string,*node] substituted nothing, so `e.value.match(...)` and
   8  // `e.key` did not resolve in a non-generic method and src/net/http's routing
   9  // tree laundered the field through concrete parameter types. This pins the
  10  // direct form; the same file with `entry` declared first compiled before the
  11  // fix, so declaration order is part of the shape, not incidental.
  12  package main
  13  
  14  import (
  15  	"fmt"
  16  	"os"
  17  )
  18  
  19  type mapping[K comparable, V comparable] struct {
  20  	s []entry[K, V]
  21  }
  22  
  23  type entry[K comparable, V comparable] struct {
  24  	key   K
  25  	value V
  26  }
  27  
  28  type node struct {
  29  	name string
  30  	hits int32
  31  }
  32  
  33  func (n *node) match(want string) (got *node, ok bool) {
  34  	if n.name == want {
  35  		return n, true
  36  	}
  37  	return nil, false
  38  }
  39  
  40  func (n *node) bump() {
  41  	n.hits = n.hits + 1
  42  }
  43  
  44  type tree struct {
  45  	children mapping[string, *node]
  46  }
  47  
  48  // scan ranges the instantiated generic's slice field and calls through the
  49  // element's pointer field: the method call behind the laundered helper.
  50  func (t *tree) scan(want string) (hits int32) {
  51  	for _, e := range t.children.s {
  52  		mp, _ := e.value.match(want)
  53  		if mp != nil {
  54  			mp.bump()
  55  			hits = hits + 1
  56  		}
  57  	}
  58  	return hits
  59  }
  60  
  61  // keyFor reads the element's key field: the map index behind the other helper.
  62  func (t *tree) keyFor(want string) (k string) {
  63  	for _, e := range t.children.s {
  64  		if e.value.name == want {
  65  			k = e.key
  66  		}
  67  	}
  68  	return k
  69  }
  70  
  71  func main() {
  72  	// Termination: a batch program must still be stoppable, so the entry
  73  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  74  	select {
  75  	case <-shutdown:
  76  		return
  77  	default:
  78  	}
  79  
  80  	t := &tree{}
  81  	t.children.s = []entry[string, *node]{}
  82  	t.children.s = push(t.children.s, entry[string, *node]{key: "a", value: &node{name: "a"}})
  83  	h := t.scan("a")
  84  	k := t.keyFor("a")
  85  	if h != 1 || k != "a" || t.children.s[0].value.hits != 1 {
  86  		fmt.Printf("FAIL forward generic field: hits=%d key=[%s]\n", h, k)
  87  		os.Exit(1)
  88  	}
  89  	fmt.Printf("ok   forward generic field: %s %d\n", k, h)
  90  }
  91