github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/go/ssa/builder_go117_test.go (about)

     1  // Copyright 2021 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  //go:build go1.17
     6  // +build go1.17
     7  
     8  package ssa_test
     9  
    10  import (
    11  	"go/ast"
    12  	"go/importer"
    13  	"go/parser"
    14  	"go/token"
    15  	"go/types"
    16  	"testing"
    17  
    18  	"golang.org/x/tools/go/ssa"
    19  	"golang.org/x/tools/go/ssa/ssautil"
    20  )
    21  
    22  func TestBuildPackageGo117(t *testing.T) {
    23  	tests := []struct {
    24  		name     string
    25  		src      string
    26  		importer types.Importer
    27  	}{
    28  		{"slice to array pointer", "package p; var s []byte; var _ = (*[4]byte)(s)", nil},
    29  		{"unsafe slice", `package p; import "unsafe"; var _ = unsafe.Add(nil, 0)`, importer.Default()},
    30  		{"unsafe add", `package p; import "unsafe"; var _ = unsafe.Slice((*int)(nil), 0)`, importer.Default()},
    31  	}
    32  
    33  	for _, tc := range tests {
    34  		tc := tc
    35  		t.Run(tc.name, func(t *testing.T) {
    36  			t.Parallel()
    37  			fset := token.NewFileSet()
    38  			f, err := parser.ParseFile(fset, "p.go", tc.src, parser.ParseComments)
    39  			if err != nil {
    40  				t.Error(err)
    41  			}
    42  			files := []*ast.File{f}
    43  
    44  			pkg := types.NewPackage("p", "")
    45  			conf := &types.Config{Importer: tc.importer}
    46  			if _, _, err := ssautil.BuildPackage(conf, fset, pkg, files, ssa.SanityCheckFunctions); err != nil {
    47  				t.Errorf("unexpected error: %v", err)
    48  			}
    49  		})
    50  	}
    51  }
    52  
    53  func TestBuildPackageFailuresGo117(t *testing.T) {
    54  	tests := []struct {
    55  		name     string
    56  		src      string
    57  		importer types.Importer
    58  	}{
    59  		{"slice to array pointer - source is not a slice", "package p; var s [4]byte; var _ = (*[4]byte)(s)", nil},
    60  		{"slice to array pointer - dest pointer elem is not an array", "package p; var s []byte; var _ = (*byte)(s)", nil},
    61  	}
    62  
    63  	for _, tc := range tests {
    64  		tc := tc
    65  		t.Run(tc.name, func(t *testing.T) {
    66  			t.Parallel()
    67  			fset := token.NewFileSet()
    68  			f, err := parser.ParseFile(fset, "p.go", tc.src, parser.ParseComments)
    69  			if err != nil {
    70  				t.Error(err)
    71  			}
    72  			files := []*ast.File{f}
    73  
    74  			pkg := types.NewPackage("p", "")
    75  			conf := &types.Config{Importer: tc.importer}
    76  			if _, _, err := ssautil.BuildPackage(conf, fset, pkg, files, ssa.SanityCheckFunctions); err == nil {
    77  				t.Error("want error, but got nil")
    78  			}
    79  		})
    80  	}
    81  }