Source file test/typeparam/dictionaryCapture-noinline.go

     1  // run -gcflags="-l"
     2  
     3  // Copyright 2021 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  // Test situations where functions/methods are not
     8  // immediately called and we need to capture the dictionary
     9  // required for later invocation.
    10  
    11  package main
    12  
    13  func main() {
    14  	functions()
    15  	methodExpressions()
    16  	methodValues()
    17  	interfaceMethods()
    18  	globals()
    19  }
    20  
    21  func g0[T any](x T) {
    22  }
    23  func g1[T any](x T) T {
    24  	return x
    25  }
    26  func g2[T any](x T) (T, T) {
    27  	return x, x
    28  }
    29  
    30  func functions() {
    31  	f0 := g0[int]
    32  	f0(7)
    33  	f1 := g1[int]
    34  	is7(f1(7))
    35  	f2 := g2[int]
    36  	is77(f2(7))
    37  }
    38  
    39  func is7(x int) {
    40  	if x != 7 {
    41  		println(x)
    42  		panic("assertion failed")
    43  	}
    44  }
    45  func is77(x, y int) {
    46  	if x != 7 || y != 7 {
    47  		println(x, y)
    48  		panic("assertion failed")
    49  	}
    50  }
    51  
    52  type s[T any] struct {
    53  	a T
    54  }
    55  
    56  func (x s[T]) g0() {
    57  }
    58  func (x s[T]) g1() T {
    59  	return x.a
    60  }
    61  func (x s[T]) g2() (T, T) {
    62  	return x.a, x.a
    63  }
    64  
    65  func methodExpressions() {
    66  	x := s[int]{a: 7}
    67  	f0 := s[int].g0
    68  	f0(x)
    69  	f1 := s[int].g1
    70  	is7(f1(x))
    71  	f2 := s[int].g2
    72  	is77(f2(x))
    73  }
    74  
    75  func methodValues() {
    76  	x := s[int]{a: 7}
    77  	f0 := x.g0
    78  	f0()
    79  	f1 := x.g1
    80  	is7(f1())
    81  	f2 := x.g2
    82  	is77(f2())
    83  }
    84  
    85  var x interface {
    86  	g0()
    87  	g1() int
    88  	g2() (int, int)
    89  } = s[int]{a: 7}
    90  var y interface{} = s[int]{a: 7}
    91  
    92  func interfaceMethods() {
    93  	x.g0()
    94  	is7(x.g1())
    95  	is77(x.g2())
    96  	y.(interface{ g0() }).g0()
    97  	is7(y.(interface{ g1() int }).g1())
    98  	is77(y.(interface{ g2() (int, int) }).g2())
    99  }
   100  
   101  // Also check for instantiations outside functions.
   102  var gg0 = g0[int]
   103  var gg1 = g1[int]
   104  var gg2 = g2[int]
   105  
   106  var hh0 = s[int].g0
   107  var hh1 = s[int].g1
   108  var hh2 = s[int].g2
   109  
   110  var xtop = s[int]{a: 7}
   111  var ii0 = x.g0
   112  var ii1 = x.g1
   113  var ii2 = x.g2
   114  
   115  func globals() {
   116  	gg0(7)
   117  	is7(gg1(7))
   118  	is77(gg2(7))
   119  	x := s[int]{a: 7}
   120  	hh0(x)
   121  	is7(hh1(x))
   122  	is77(hh2(x))
   123  	ii0()
   124  	is7(ii1())
   125  	is77(ii2())
   126  }
   127  

View as plain text