-
Notifications
You must be signed in to change notification settings - Fork 4
/
inspect.go
338 lines (261 loc) · 7.74 KB
/
inspect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package inspect
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2023 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"path"
"reflect"
"sort"
"strings"
"github.com/kisielk/gotool"
"golang.org/x/tools/go/packages"
"github.com/essentialkaos/aligo/v2/report"
)
// ////////////////////////////////////////////////////////////////////////////////// //
const IGNORE_FLAG = "aligo:ignore"
// ////////////////////////////////////////////////////////////////////////////////// //
// Sizes contains info about WordSize and MaxAlign
var Sizes types.Sizes
// ////////////////////////////////////////////////////////////////////////////////// //
type structInfo struct {
Name string
Type *types.Struct
AST *ast.StructType
Pos token.Position
Mappings map[string]string
Skip bool
}
// ////////////////////////////////////////////////////////////////////////////////// //
var fileSet *token.FileSet
// ////////////////////////////////////////////////////////////////////////////////// //
// ProcessSources starts sources processing
func ProcessSources(dirs, tags []string) (*report.Report, error) {
importPaths := gotool.ImportPaths(dirs)
if len(importPaths) == 0 {
return nil, fmt.Errorf("No import paths found")
}
fileSet = token.NewFileSet()
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedTypes | packages.NeedTypesInfo | packages.NeedSyntax,
Fset: fileSet,
Tests: false,
}, importPaths...)
if err != nil {
return nil, err
}
return processPackages(pkgs)
}
// GetMaxAlign returns MaxAlign
func GetMaxAlign() int64 {
if Sizes == nil {
return 8
}
switch t := Sizes.(type) {
case *types.StdSizes:
return t.MaxAlign
}
// Get MaxAlign from private struct like *types.gcSizes
ptr := reflect.ValueOf(Sizes)
if ptr.IsValid() {
f := reflect.Indirect(ptr).FieldByName("MaxAlign")
if f.IsValid() {
return f.Int()
}
}
return 8
}
// ////////////////////////////////////////////////////////////////////////////////// //
func processPackages(pkgs []*packages.Package) (*report.Report, error) {
result := &report.Report{}
for _, pkg := range pkgs {
pkgInfo, err := processPackage(pkg)
if err != nil {
return nil, err
}
result.Packages = append(result.Packages, pkgInfo)
}
return result, nil
}
func processPackage(pkg *packages.Package) (*report.Package, error) {
var strName string
var strPos token.Position
var strIgnore bool
result := &report.Package{Path: pkg.ID}
mappings := map[string]string{pkg.ID + ".": ""}
for _, file := range pkg.Syntax {
commentMap := ast.NewCommentMap(fileSet, file, file.Comments)
ast.Inspect(file, func(node ast.Node) bool {
switch nt := node.(type) {
case *ast.GenDecl:
if nt.Tok == token.TYPE {
decl := nt.Specs[0].(*ast.TypeSpec)
strName = decl.Name.Name
strPos = fileSet.Position(nt.TokPos)
strIgnore = checkIgnoreFlag(commentMap.Filter(nt))
}
case *ast.ImportSpec:
ntPath := strings.Trim(nt.Path.Value, `"`)
if strings.Contains(ntPath, "/") {
if nt.Name == nil {
mappings[ntPath] = formatPackageName(ntPath)
} else {
mappings[ntPath] = nt.Name.Name
}
}
case *ast.StructType:
if strName == "" {
return true // ignore unnamed structs defined in methods
}
info := &structInfo{
Name: strName,
Type: pkg.TypesInfo.Types[nt].Type.(*types.Struct),
AST: nt,
Pos: strPos,
Mappings: mappings,
Skip: strIgnore,
}
structReport := getStructReport(info)
if structReport != nil {
result.Structs = append(result.Structs, structReport)
}
strName = ""
}
return true
})
}
return result, nil
}
// getStructInfo parses struct info and calculates size
func getStructReport(info *structInfo) *report.Struct {
result := &report.Struct{
Name: info.Name,
Position: convertPosition(info.Pos),
Ignore: info.Skip,
}
numFields := info.Type.NumFields()
for i := 0; i < numFields; i++ {
f := info.Type.Field(i)
fs := info.AST.Fields.List[i]
size := Sizes.Sizeof(f.Type().Underlying())
comm := strings.Trim(fs.Comment.Text(), "\n\r")
typ := formatValueType(f.Type().String(), info.Mappings)
result.Fields = append(
result.Fields,
&report.Field{
Name: f.Name(),
Type: typ,
Tag: info.Type.Tag(i),
Comment: comm,
Size: size,
},
)
}
// Recover from panic of checking size of generic types
defer func() { recover() }()
result.Size = Sizes.Sizeof(info.Type)
alnSize, alnFields := getAlignedFields(info.Type, result.Fields)
if alnSize != result.Size {
result.OptimalSize = alnSize
result.AlignedFields = alnFields
} else {
result.OptimalSize = result.Size
}
return result
}
// getAlignedFields tries to find optimal field order
func getAlignedFields(str *types.Struct, origFields []*report.Field) (int64, []*report.Field) {
numFields := len(origFields)
fields := append(origFields[:0:0], origFields...)
vars := make([]*types.Var, numFields)
aligns := make([]int64, numFields)
sizes := make([]int64, numFields)
for i := 0; i < numFields; i++ {
fieldVar := str.Field(i)
vars[i] = fieldVar
aligns[i] = Sizes.Alignof(fieldVar.Type())
sizes[i] = fields[i].Size
}
sort.Stable(&optimalSorter{vars, fields, aligns, sizes})
return Sizes.Sizeof(types.NewStruct(vars, nil)), fields
}
// convertPosition converts position between types
func convertPosition(pos token.Position) report.Position {
return report.Position{
File: path.Base(pos.Filename),
Line: pos.Line,
}
}
// formatValueType formats value type
func formatValueType(typ string, mappings map[string]string) string {
for k, v := range mappings {
if strings.Contains(typ, k) {
typ = strings.ReplaceAll(typ, k, v)
}
}
if strings.ContainsRune(typ, '/') {
return path.Base(typ)
}
return typ
}
// formatPackageName formats package name
func formatPackageName(p string) string {
p = path.Base(p)
p = strings.ReplaceAll(p, "go-", "")
p = strings.ReplaceAll(p, "go.", "")
if strings.Contains(p, ".") {
p = p[:strings.Index(p, ".")]
}
return p
}
// checkIgnoreFlag checks struct comments for ignore flag
func checkIgnoreFlag(cm ast.CommentMap) bool {
if cm == nil || len(cm.Comments()) == 0 {
return false
}
for _, cg := range cm.Comments() {
for _, c := range cg.List {
if strings.Contains(strings.ToLower(c.Text), IGNORE_FLAG) {
return true
}
}
}
return false
}
// ////////////////////////////////////////////////////////////////////////////////// //
// optimalSorter is field sorter
type optimalSorter struct {
Vars []*types.Var
Fields []*report.Field
Aligns []int64
Sizes []int64
}
func (s *optimalSorter) Len() int {
return len(s.Fields)
}
func (s *optimalSorter) Swap(i, j int) {
s.Vars[i], s.Vars[j] = s.Vars[j], s.Vars[i]
s.Fields[i], s.Fields[j] = s.Fields[j], s.Fields[i]
s.Aligns[i], s.Aligns[j] = s.Aligns[j], s.Aligns[i]
s.Sizes[i], s.Sizes[j] = s.Sizes[j], s.Sizes[i]
}
func (s *optimalSorter) Less(i, j int) bool {
switch {
case s.Sizes[i] == 0 && s.Sizes[j] != 0,
s.Sizes[j] == 0 && s.Sizes[i] != 0:
return false
case s.Aligns[i] != s.Aligns[j]:
return s.Aligns[i] > s.Aligns[j]
case s.Sizes[i] != s.Sizes[j]:
return s.Sizes[i] > s.Sizes[j]
default:
return false
}
}
// ////////////////////////////////////////////////////////////////////////////////// //