golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/internal/typeparams/free_test.go (about)

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package typeparams
     6  
     7  import (
     8  	"go/ast"
     9  	"go/parser"
    10  	"go/token"
    11  	"go/types"
    12  	"testing"
    13  )
    14  
    15  func TestFree(t *testing.T) {
    16  	const source = `
    17  package P
    18  type A int
    19  func (A) f()
    20  func (*A) g()
    21  
    22  type fer interface { f() }
    23  
    24  func Apply[T fer](x T) T {
    25  	x.f()
    26  	return x
    27  }
    28  
    29  type V[T any] []T
    30  func (v *V[T]) Push(x T) { *v = append(*v, x) }
    31  `
    32  
    33  	fset := token.NewFileSet()
    34  	f, err := parser.ParseFile(fset, "hello.go", source, 0)
    35  	if err != nil {
    36  		t.Fatal(err)
    37  	}
    38  
    39  	var conf types.Config
    40  	pkg, err := conf.Check("P", fset, []*ast.File{f}, nil)
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  
    45  	for _, test := range []struct {
    46  		expr string // type expression
    47  		want bool   // expected value
    48  	}{
    49  		{"A", false},
    50  		{"*A", false},
    51  		{"error", false},
    52  		{"*error", false},
    53  		{"struct{A}", false},
    54  		{"*struct{A}", false},
    55  		{"fer", false},
    56  		{"Apply", true},
    57  		{"Apply[A]", false},
    58  		{"V", true},
    59  		{"V[A]", false},
    60  		{"*V[A]", false},
    61  		{"(*V[A]).Push", false},
    62  	} {
    63  		tv, err := types.Eval(fset, pkg, 0, test.expr)
    64  		if err != nil {
    65  			t.Errorf("Eval(%s) failed: %v", test.expr, err)
    66  		}
    67  
    68  		if got := new(Free).Has(tv.Type); got != test.want {
    69  			t.Logf("Eval(%s) returned the type %s", test.expr, tv.Type)
    70  			t.Errorf("isParameterized(%s) = %v, want %v", test.expr, got, test.want)
    71  		}
    72  	}
    73  }