1 // keyify transforms unkeyed struct literals into a keyed ones.
19 "honnef.co/go/tools/version"
21 "golang.org/x/tools/go/ast/astutil"
22 "golang.org/x/tools/go/buildutil"
23 "golang.org/x/tools/go/loader"
36 flag.BoolVar(&fRecursive, "r", false, "keyify struct initializers recursively")
37 flag.BoolVar(&fOneLine, "o", false, "print new struct initializer on a single line")
38 flag.BoolVar(&fJSON, "json", false, "print new struct initializer as JSON")
39 flag.BoolVar(&fMinify, "m", false, "omit fields that are set to their zero value")
40 flag.BoolVar(&fModified, "modified", false, "read an archive of modified files from standard input")
41 flag.BoolVar(&fVersion, "version", false, "Print version and exit")
45 fmt.Printf("Usage: %s [flags] <position>\n\n", os.Args[0])
64 name, start, _, err := parsePos(pos)
68 eval, err := filepath.EvalSymlinks(name)
72 name, err = filepath.Abs(eval)
76 cwd, err := os.Getwd()
82 overlay, err := buildutil.ParseOverlayArchive(os.Stdin)
86 ctx = buildutil.OverlayContext(ctx, overlay)
88 bpkg, err := buildutil.ContainingPackage(ctx, cwd, name)
92 conf := &loader.Config{
95 conf.TypeCheckFuncBodies = func(s string) bool {
96 return s == bpkg.ImportPath || s == bpkg.ImportPath+"_test"
98 conf.ImportWithTests(bpkg.ImportPath)
99 lprog, err := conf.Load()
105 var pkg *loader.PackageInfo
107 for _, pkg = range lprog.InitialPackages() {
108 for _, ff := range pkg.Files {
109 file := lprog.Fset.File(ff.Pos())
110 if file.Name() == name {
118 log.Fatalf("couldn't find file %s", name)
120 tstart, tend, err := fileOffsetToPos(tf, start, start)
124 path, _ := astutil.PathEnclosingInterval(af, tstart, tend)
125 var complit *ast.CompositeLit
126 for _, p := range path {
127 if p, ok := p.(*ast.CompositeLit); ok {
133 log.Fatal("no composite literal found near point")
135 if len(complit.Elts) == 0 {
136 printComplit(complit, complit, lprog.Fset, lprog.Fset)
139 if _, ok := complit.Elts[0].(*ast.KeyValueExpr); ok {
142 lit = copyExpr(complit, 1).(*ast.CompositeLit)
144 printComplit(complit, lit, lprog.Fset, lprog.Fset)
147 _, ok := pkg.TypeOf(complit).Underlying().(*types.Struct)
149 log.Fatal("not a struct initialiser")
153 newComplit, lines := keyify(pkg, complit)
154 newFset := token.NewFileSet()
155 newFile := newFset.AddFile("", -1, lines)
156 for i := 1; i <= lines; i++ {
159 printComplit(complit, newComplit, lprog.Fset, newFset)
163 pkg *loader.PackageInfo,
164 complit *ast.CompositeLit,
165 ) (*ast.CompositeLit, int) {
166 var calcPos func(int) token.Pos
168 calcPos = func(int) token.Pos { return token.Pos(1) }
170 calcPos = func(i int) token.Pos { return token.Pos(2 + i) }
173 st, _ := pkg.TypeOf(complit).Underlying().(*types.Struct)
174 newComplit := &ast.CompositeLit{
177 Rbrace: token.Pos(st.NumFields() + 2),
180 newComplit.Rbrace = 1
182 numLines := 2 + st.NumFields()
184 for i := 0; i < st.NumFields(); i++ {
186 val := complit.Elts[i]
188 if val2, ok := val.(*ast.CompositeLit); ok {
189 if _, ok := pkg.TypeOf(val2.Type).Underlying().(*types.Struct); ok {
190 // FIXME(dh): this code is obviously wrong. But
191 // what were we intending to do here?
194 //lint:ignore SA4006 See FIXME above.
195 val, lines = keyify(pkg, val2)
199 _, isIface := st.Field(i).Type().Underlying().(*types.Interface)
200 if fMinify && (isNil(val, pkg) || (!isIface && isZero(val, pkg))) {
203 elt := &ast.KeyValueExpr{
204 Key: &ast.Ident{NamePos: calcPos(n), Name: field.Name()},
205 Value: copyExpr(val, calcPos(n)),
207 newComplit.Elts = append(newComplit.Elts, elt)
210 return newComplit, numLines
213 func isNil(val ast.Expr, pkg *loader.PackageInfo) bool {
214 ident, ok := val.(*ast.Ident)
218 if _, ok := pkg.ObjectOf(ident).(*types.Nil); ok {
221 if c, ok := pkg.ObjectOf(ident).(*types.Const); ok {
222 if c.Val().Kind() != constant.Bool {
225 return !constant.BoolVal(c.Val())
230 func isZero(val ast.Expr, pkg *loader.PackageInfo) bool {
231 switch val := val.(type) {
234 case `""`, "``", "0", "0.0", "0i", "0.":
240 return isNil(val, pkg)
241 case *ast.CompositeLit:
242 typ := pkg.TypeOf(val.Type)
247 switch typ := typ.Underlying().(type) {
250 _, isIface = typ.Elem().Underlying().(*types.Interface)
254 for _, elt := range val.Elts {
255 if isNil(elt, pkg) || (!isIface && !isZero(elt, pkg)) {
264 func printComplit(oldlit, newlit *ast.CompositeLit, oldfset, newfset *token.FileSet) {
265 buf := &bytes.Buffer{}
266 cfg := printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
267 _ = cfg.Fprint(buf, newfset, newlit)
270 Start int `json:"start"`
272 Replacement string `json:"replacement"`
274 oldfset.Position(oldlit.Pos()).Offset,
275 oldfset.Position(oldlit.End()).Offset,
278 _ = json.NewEncoder(os.Stdout).Encode(output)
280 fmt.Println(buf.String())
284 func copyExpr(expr ast.Expr, line token.Pos) ast.Expr {
285 switch expr := expr.(type) {
290 case *ast.BinaryExpr:
292 cp.X = copyExpr(cp.X, line)
294 cp.Y = copyExpr(cp.Y, line)
298 cp.Fun = copyExpr(cp.Fun, line)
300 for i, v := range cp.Args {
301 cp.Args[i] = copyExpr(v, line)
303 if cp.Ellipsis != 0 {
308 case *ast.CompositeLit:
310 cp.Type = copyExpr(cp.Type, line)
312 for i, v := range cp.Elts {
313 cp.Elts[i] = copyExpr(v, line)
323 cp.X = copyExpr(cp.X, line)
325 cp.Index = copyExpr(cp.Index, line)
328 case *ast.KeyValueExpr:
330 cp.Key = copyExpr(cp.Key, line)
332 cp.Value = copyExpr(cp.Value, line)
337 cp.X = copyExpr(cp.X, line)
340 case *ast.SelectorExpr:
342 cp.X = copyExpr(cp.X, line)
343 cp.Sel = copyExpr(cp.Sel, line).(*ast.Ident)
347 cp.X = copyExpr(cp.X, line)
349 cp.Low = copyExpr(cp.Low, line)
350 cp.High = copyExpr(cp.High, line)
351 cp.Max = copyExpr(cp.Max, line)
357 cp.X = copyExpr(cp.X, line)
359 case *ast.TypeAssertExpr:
361 cp.X = copyExpr(cp.X, line)
363 cp.Type = copyExpr(cp.Type, line)
369 cp.X = copyExpr(cp.X, line)
374 cp.Key = copyExpr(cp.Key, line)
375 cp.Value = copyExpr(cp.Value, line)
380 cp.Len = copyExpr(cp.Len, line)
381 cp.Elt = copyExpr(cp.Elt, line)
385 cp.Elt = copyExpr(cp.Elt, line)
388 case *ast.InterfaceType:
392 case *ast.StructType:
402 cp.Value = copyExpr(cp.Value, line)
407 panic(fmt.Sprintf("shouldn't happen: unknown ast.Expr of type %T", expr))