github.com/orijtech/structslop@v0.0.9-0.20230520012622-069644583b8b/fields_preserve_test.go (about)

     1  // Copyright 2020 Orijtech, Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package structslop
    16  
    17  import (
    18  	"go/ast"
    19  	"go/build"
    20  	"go/importer"
    21  	"go/parser"
    22  	"go/token"
    23  	"go/types"
    24  	"testing"
    25  )
    26  
    27  func TestStructFieldsPreserve(t *testing.T) {
    28  	src := `package p
    29  type s struct {
    30  	_  [0]func()
    31  	a3 [3]bool
    32  	i int
    33  }
    34  `
    35  	fset := token.NewFileSet()
    36  	f, err := parser.ParseFile(fset, "struct_fields_preserve.go", src, 0)
    37  	if err != nil {
    38  		t.Fatal(err)
    39  	}
    40  
    41  	conf := types.Config{Importer: importer.Default()}
    42  	info := &types.Info{Types: make(map[ast.Expr]types.TypeAndValue)}
    43  	if _, err := conf.Check("", fset, []*ast.File{f}, info); err != nil {
    44  		t.Fatal(err)
    45  	}
    46  
    47  	stdSizes := types.SizesFor(build.Default.Compiler, build.Default.GOARCH)
    48  	sizes := &sizes{
    49  		stdSizes: stdSizes,
    50  		maxAlign: stdSizes.Alignof(types.Unsafe.Scope().Lookup("Pointer").(*types.TypeName).Type()),
    51  	}
    52  
    53  	ast.Inspect(f, func(n ast.Node) bool {
    54  		if atyp, ok := n.(*ast.StructType); ok {
    55  			if tv, ok := info.Types[atyp]; ok {
    56  				styp := tv.Type.(*types.Struct)
    57  				optStruct := optimalStructArrangement(sizes, mapFieldIdx(styp))
    58  				if optStruct.Field(0) != styp.Field(0) {
    59  					t.Errorf("%v field order changed", styp.Field(0))
    60  				}
    61  			}
    62  		}
    63  
    64  		return true
    65  	})
    66  }