Source file src/go/types/alias_test.go

     1  // Copyright 2025 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 types_test
     6  
     7  import (
     8  	"go/ast"
     9  	"go/parser"
    10  	"go/token"
    11  	"go/types"
    12  	"testing"
    13  )
    14  
    15  func TestIssue74181(t *testing.T) {
    16  	t.Setenv("GODEBUG", "gotypesalias=1")
    17  
    18  	src := `package p
    19  
    20  type AB = A[B]
    21  
    22  type _ struct {
    23  	_ AB
    24  }
    25  
    26  type B struct {
    27  	f *AB
    28  }
    29  
    30  type A[T any] struct{}`
    31  
    32  	fset := token.NewFileSet()
    33  	file, err := parser.ParseFile(fset, "p.go", src, parser.ParseComments)
    34  	if err != nil {
    35  		t.Fatalf("could not parse: %v", err)
    36  	}
    37  
    38  	conf := types.Config{}
    39  	pkg, err := conf.Check(file.Name.Name, fset, []*ast.File{file}, &types.Info{})
    40  	if err != nil {
    41  		t.Fatalf("could not type check: %v", err)
    42  	}
    43  
    44  	b := pkg.Scope().Lookup("B").Type()
    45  	if n, ok := b.(*types.Named); ok {
    46  		if s, ok := n.Underlying().(*types.Struct); ok {
    47  			got := s.Field(0).Type()
    48  			want := types.NewPointer(pkg.Scope().Lookup("AB").Type())
    49  			if !types.Identical(got, want) {
    50  				t.Errorf("wrong type for f: got %v, want %v", got, want)
    51  			}
    52  			return
    53  		}
    54  	}
    55  	t.Errorf("unexpected type for B: %v", b)
    56  }
    57  
    58  func TestPartialTypeCheckUndeclaredAliasPanic(t *testing.T) {
    59  	t.Setenv("GODEBUG", "gotypesalias=1")
    60  
    61  	src := `package p
    62  
    63  type A = B // undeclared`
    64  
    65  	fset := token.NewFileSet()
    66  	file, err := parser.ParseFile(fset, "p.go", src, parser.ParseComments)
    67  	if err != nil {
    68  		t.Fatalf("could not parse: %v", err)
    69  	}
    70  
    71  	conf := types.Config{} // no error handler, panic
    72  	pkg, _ := conf.Check(file.Name.Name, fset, []*ast.File{file}, &types.Info{})
    73  	a := pkg.Scope().Lookup("A").Type()
    74  
    75  	if alias, ok := a.(*types.Alias); ok {
    76  		got := alias.Rhs()
    77  		want := types.Typ[types.Invalid]
    78  
    79  		if !types.Identical(got, want) {
    80  			t.Errorf("wrong type for B: got %v, want %v", got, want)
    81  		}
    82  		return
    83  	}
    84  	t.Errorf("unexpected type for A: %v", a)
    85  }
    86  

View as plain text