-
Notifications
You must be signed in to change notification settings - Fork 21
/
key.go
77 lines (69 loc) · 1.79 KB
/
key.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
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"go/ast"
"go/types"
"rsc.io/rf/refactor"
)
func cmdKey(snap *refactor.Snapshot, args string) error {
items, _ := snap.EvalList(args)
if len(items) == 0 {
return newErrUsage("key StructType...")
}
var fixing []types.Type
for _, item := range items {
if item == nil {
continue
}
if item.Kind == refactor.ItemNotFound {
return newErrPrecondition("%s not found", item.Name)
}
if item.Kind != refactor.ItemType {
return newErrPrecondition("%s is not a type", item.Name)
}
typ := item.Obj.(*types.TypeName).Type().(*types.Named)
if _, ok := typ.Underlying().(*types.Struct); !ok {
return newErrPrecondition("%s is not a struct type", item.Name)
}
fixing = append(fixing, typ)
}
if snap.Errors.Err() != nil {
// Abort early.
return nil
}
keyLiterals(snap, fixing)
return nil
}
func keyLiterals(snap *refactor.Snapshot, list []types.Type) {
fixing := make(map[types.Type]bool)
for _, t := range list {
fixing[t] = true
}
snap.ForEachFile(func(pkg *refactor.Package, file *ast.File) {
refactor.Walk(file, func(stack []ast.Node) {
lit, ok := stack[0].(*ast.CompositeLit)
if !ok || len(lit.Elts) == 0 || lit.Incomplete {
return
}
if _, ok := lit.Elts[0].(*ast.KeyValueExpr); ok {
// already keyed
return
}
typ := pkg.TypesInfo.TypeOf(lit)
if !fixing[typ] {
return
}
struc := typ.Underlying().(*types.Struct)
if struc.NumFields() != len(lit.Elts) {
snap.ErrorAt(lit.Pos(), "wrong number of struct literal initializers")
return
}
for i, e := range lit.Elts {
f := struc.Field(i)
snap.InsertAt(e.Pos(), f.Name()+":")
}
})
})
}