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

     1  // Copyright 2024 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 aliases_test
     6  
     7  import (
     8  	"go/ast"
     9  	"go/parser"
    10  	"go/token"
    11  	"go/types"
    12  	"testing"
    13  
    14  	"golang.org/x/tools/internal/aliases"
    15  	"golang.org/x/tools/internal/testenv"
    16  )
    17  
    18  // Assert that Obj exists on Alias.
    19  var _ func(*aliases.Alias) *types.TypeName = (*aliases.Alias).Obj
    20  
    21  // TestNewAlias tests that alias.NewAlias creates an alias of a type
    22  // whose underlying and Unaliased type is *Named.
    23  // When gotypesalias=1 (or unset) and GoVersion >= 1.22, the type will
    24  // be an *aliases.Alias.
    25  func TestNewAlias(t *testing.T) {
    26  	const source = `
    27  	package P
    28  
    29  	type Named int
    30  	`
    31  	fset := token.NewFileSet()
    32  	f, err := parser.ParseFile(fset, "hello.go", source, 0)
    33  	if err != nil {
    34  		t.Fatal(err)
    35  	}
    36  
    37  	var conf types.Config
    38  	pkg, err := conf.Check("P", fset, []*ast.File{f}, nil)
    39  	if err != nil {
    40  		t.Fatal(err)
    41  	}
    42  
    43  	expr := `*Named`
    44  	tv, err := types.Eval(fset, pkg, 0, expr)
    45  	if err != nil {
    46  		t.Fatalf("Eval(%s) failed: %v", expr, err)
    47  	}
    48  
    49  	for _, godebug := range []string{
    50  		// "", // The default is in transition; suppress this case for now
    51  		"gotypesalias=0",
    52  		"gotypesalias=1"} {
    53  		t.Run(godebug, func(t *testing.T) {
    54  			t.Setenv("GODEBUG", godebug)
    55  
    56  			enabled := aliases.Enabled()
    57  
    58  			A := aliases.NewAlias(enabled, token.NoPos, pkg, "A", tv.Type)
    59  			if got, want := A.Name(), "A"; got != want {
    60  				t.Errorf("Expected A.Name()==%q. got %q", want, got)
    61  			}
    62  
    63  			if got, want := A.Type().Underlying(), tv.Type; got != want {
    64  				t.Errorf("Expected A.Type().Underlying()==%q. got %q", want, got)
    65  			}
    66  			if got, want := aliases.Unalias(A.Type()), tv.Type; got != want {
    67  				t.Errorf("Expected Unalias(A)==%q. got %q", want, got)
    68  			}
    69  
    70  			if testenv.Go1Point() >= 22 && godebug != "gotypesalias=0" {
    71  				if _, ok := A.Type().(*aliases.Alias); !ok {
    72  					t.Errorf("Expected A.Type() to be a types.Alias(). got %q", A.Type())
    73  				}
    74  			}
    75  		})
    76  	}
    77  }