Skip to content

Commit 3fd37e5

Browse files
committed
internal/lsp: added a code action which generates key-value pairs of individual
fields and default values between a struct's enclosing braces Fixes #37576
1 parent a64b766 commit 3fd37e5

21 files changed

+401
-0
lines changed

internal/lsp/cmd/test/fillstruct.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package cmdtest
2+
3+
import (
4+
"testing"
5+
6+
"golang.org/x/tools/internal/span"
7+
)
8+
9+
func (r *runner) RefactorRewrite(t *testing.T, spn span.Span, title string) {}

internal/lsp/code_action.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,11 @@ func (s *Server) codeAction(ctx context.Context, params *protocol.CodeActionPara
143143
})
144144
}
145145
}
146+
fillActions, err := source.FillStruct(ctx, snapshot, fh, params.Range)
147+
if err != nil {
148+
return nil, err
149+
}
150+
codeActions = append(codeActions, fillActions...)
146151
default:
147152
// Unsupported file kind for a code action.
148153
return nil, nil

internal/lsp/lsp_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,47 @@ func (r *runner) Import(t *testing.T, spn span.Span) {
369369
}
370370
}
371371

372+
func (r *runner) RefactorRewrite(t *testing.T, spn span.Span, title string) {
373+
uri := spn.URI()
374+
m, err := r.data.Mapper(uri)
375+
if err != nil {
376+
t.Fatal(err)
377+
}
378+
rng, err := m.Range(spn)
379+
if err != nil {
380+
t.Fatal(err)
381+
}
382+
actions, err := r.server.CodeAction(r.ctx, &protocol.CodeActionParams{
383+
TextDocument: protocol.TextDocumentIdentifier{
384+
URI: protocol.URIFromSpanURI(uri),
385+
},
386+
Range: rng,
387+
})
388+
389+
if len(actions) == 0 {
390+
return
391+
}
392+
for _, action := range actions {
393+
fmt.Printf("%v\n", action)
394+
if action.Kind == protocol.RefactorRewrite && action.Title == title {
395+
res, err := applyWorkspaceEdits(r, action.Edit)
396+
if err != nil {
397+
t.Fatal(err)
398+
}
399+
for u, got := range res {
400+
fixed := string(r.data.Golden(tests.SpanName(spn), u.Filename(), func() ([]byte, error) {
401+
return []byte(got), nil
402+
}))
403+
if fixed != got {
404+
t.Errorf("%s failed for %s, expected:\n%#v\ngot:\n%#v", title, u.Filename(), fixed, got)
405+
}
406+
}
407+
return
408+
}
409+
}
410+
t.Fatal("expected refactor rewrite")
411+
}
412+
372413
func (r *runner) SuggestedFix(t *testing.T, spn span.Span, actionKinds []string) {
373414
uri := spn.URI()
374415
view, err := r.server.session.ViewOf(uri)

internal/lsp/source/fill_struct.go

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
// Copyright 2020 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+
package source
6+
7+
import (
8+
"context"
9+
"fmt"
10+
"go/format"
11+
"go/types"
12+
"strings"
13+
14+
"golang.org/x/tools/go/ast/astutil"
15+
"golang.org/x/tools/internal/lsp/protocol"
16+
)
17+
18+
// FillStruct completes all of targeted struct's fields with their default values.
19+
func FillStruct(ctx context.Context, snapshot Snapshot, fh FileHandle, protoRng protocol.Range) ([]protocol.CodeAction, error) {
20+
21+
pkg, pgh, err := getParsedFile(ctx, snapshot, fh, NarrowestPackageHandle)
22+
if err != nil {
23+
return nil, fmt.Errorf("getting file for struct fill code action: %v", err)
24+
}
25+
file, src, m, _, err := pgh.Cached()
26+
if err != nil {
27+
return nil, err
28+
}
29+
spn, err := m.PointSpan(protoRng.Start)
30+
if err != nil {
31+
return nil, err
32+
}
33+
spanRng, err := spn.Range(m.Converter)
34+
if err != nil {
35+
return nil, err
36+
}
37+
path, _ := astutil.PathEnclosingInterval(file, spanRng.Start, spanRng.End)
38+
if path == nil {
39+
return nil, nil
40+
}
41+
42+
ecl := enclosingCompositeLiteral(path, spanRng.Start, pkg.GetTypesInfo())
43+
if ecl == nil || !ecl.isStruct() {
44+
return nil, nil
45+
}
46+
47+
// If in F{ Bar<> : V} or anywhere in F{Bar : V, ...}
48+
// we should not fill the struct.
49+
if ecl.inKey || len(ecl.cl.Elts) != 0 {
50+
return nil, nil
51+
}
52+
53+
var codeActions []protocol.CodeAction
54+
qfFunc := qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo())
55+
switch obj := ecl.clType.(type) {
56+
case *types.Struct:
57+
fieldCount := obj.NumFields()
58+
if fieldCount == 0 {
59+
return nil, nil
60+
}
61+
var edit string
62+
for i := 0; i < fieldCount; i++ {
63+
field := obj.Field(i)
64+
// Ignore fields that are not accessible in the current package.
65+
if field.Pkg() != nil && field.Pkg() != pkg.GetTypes() && !field.Exported() {
66+
continue
67+
}
68+
69+
label := field.Name()
70+
value := formatZeroValue(field.Type(), qfFunc)
71+
text := "\n" + label + " : " + value + ","
72+
edit += text
73+
}
74+
edit += "\n"
75+
76+
// the range of all text between '<>', inclusive. E.g. {<> ... <}>
77+
mappedRange := newMappedRange(snapshot.View().Session().Cache().FileSet(), m, ecl.cl.Lbrace, ecl.cl.Rbrace+1)
78+
protoRange, err := mappedRange.Range()
79+
if err != nil {
80+
return nil, err
81+
}
82+
// consider formatting from the first character of the line the lbrace is on.
83+
// ToOffset is 1-based
84+
beginOffset, err := m.Converter.ToOffset(int(protoRange.Start.Line)+1, 1)
85+
if err != nil {
86+
return nil, err
87+
}
88+
89+
endOffset, err := m.Converter.ToOffset(int(protoRange.Start.Line)+1, int(protoRange.Start.Character)+1)
90+
if err != nil {
91+
return nil, err
92+
}
93+
94+
// An increment to make sure the lbrace is included in the slice.
95+
endOffset++
96+
// Append the edits. Then append the closing brace.
97+
sourceCode := string(src[beginOffset:endOffset]) + edit + "}"
98+
99+
buf, err := format.Source([]byte(sourceCode))
100+
if err != nil {
101+
return nil, err
102+
}
103+
104+
// it is guranteed that a left brace exists.
105+
edit = string(buf[strings.IndexByte(string(buf), '{'):])
106+
107+
codeActions = append(codeActions, protocol.CodeAction{
108+
Title: "Fill struct",
109+
Kind: protocol.RefactorRewrite,
110+
Edit: protocol.WorkspaceEdit{
111+
DocumentChanges: []protocol.TextDocumentEdit{
112+
{
113+
TextDocument: protocol.VersionedTextDocumentIdentifier{
114+
Version: fh.Identity().Version,
115+
TextDocumentIdentifier: protocol.TextDocumentIdentifier{
116+
URI: protocol.URIFromSpanURI(fh.Identity().URI),
117+
},
118+
},
119+
Edits: []protocol.TextEdit{
120+
{
121+
Range: protoRange,
122+
NewText: edit,
123+
},
124+
},
125+
},
126+
},
127+
},
128+
})
129+
}
130+
131+
return codeActions, nil
132+
}

internal/lsp/source/options.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ func DefaultOptions() Options {
8989
protocol.SourceFixAll: true,
9090
protocol.SourceOrganizeImports: true,
9191
protocol.QuickFix: true,
92+
protocol.RefactorRewrite: true,
9293
},
9394
Mod: {
9495
protocol.SourceOrganizeImports: true,

internal/lsp/source/source_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,7 @@ func (r *runner) Import(t *testing.T, spn span.Span) {
473473
}
474474

475475
func (r *runner) SuggestedFix(t *testing.T, spn span.Span, actionKinds []string) {}
476+
func (r *runner) RefactorRewrite(t *testing.T, spn span.Span, title string) {}
476477

477478
func (r *runner) Definition(t *testing.T, spn span.Span, d tests.Definition) {
478479
_, srcRng, err := spanToRange(r.data, d.Src)

internal/lsp/testdata/indirect/summary.txt.golden

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@ CaseSensitiveWorkspaceSymbolsCount = 0
2525
SignaturesCount = 0
2626
LinksCount = 0
2727
ImplementationsCount = 0
28+
FillStructCount = 0
2829

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package data
2+
3+
type A struct {
4+
ExportedInt int
5+
unexportedInt int
6+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package fillstruct
2+
3+
type StructA struct {
4+
unexportedIntField int
5+
ExportedIntField int
6+
MapA map[int]string
7+
Array []int
8+
StructB
9+
}
10+
11+
type StructA2 struct {
12+
B *StructB
13+
}
14+
15+
type StructA3 struct {
16+
B StructB
17+
}
18+
19+
func fill() {
20+
a := StructA{} //@refactorrewrite("}", "Fill struct")
21+
b := StructA2{} //@refactorrewrite("}", "Fill struct")
22+
c := StructA3{} //@refactorrewrite("}", "Fill struct")
23+
}
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
-- fill_struct_20_15 --
2+
package fillstruct
3+
4+
type StructA struct {
5+
unexportedIntField int
6+
ExportedIntField int
7+
MapA map[int]string
8+
Array []int
9+
StructB
10+
}
11+
12+
type StructA2 struct {
13+
B *StructB
14+
}
15+
16+
type StructA3 struct {
17+
B StructB
18+
}
19+
20+
func fill() {
21+
a := StructA{
22+
unexportedIntField: 0,
23+
ExportedIntField: 0,
24+
MapA: nil,
25+
Array: nil,
26+
StructB: StructB{},
27+
} //@refactorrewrite("}", "Fill struct")
28+
b := StructA2{} //@refactorrewrite("}", "Fill struct")
29+
c := StructA3{} //@refactorrewrite("}", "Fill struct")
30+
}
31+
32+
-- fill_struct_21_16 --
33+
package fillstruct
34+
35+
type StructA struct {
36+
unexportedIntField int
37+
ExportedIntField int
38+
MapA map[int]string
39+
Array []int
40+
StructB
41+
}
42+
43+
type StructA2 struct {
44+
B *StructB
45+
}
46+
47+
type StructA3 struct {
48+
B StructB
49+
}
50+
51+
func fill() {
52+
a := StructA{} //@refactorrewrite("}", "Fill struct")
53+
b := StructA2{
54+
B: nil,
55+
} //@refactorrewrite("}", "Fill struct")
56+
c := StructA3{} //@refactorrewrite("}", "Fill struct")
57+
}
58+
59+
-- fill_struct_22_16 --
60+
package fillstruct
61+
62+
type StructA struct {
63+
unexportedIntField int
64+
ExportedIntField int
65+
MapA map[int]string
66+
Array []int
67+
StructB
68+
}
69+
70+
type StructA2 struct {
71+
B *StructB
72+
}
73+
74+
type StructA3 struct {
75+
B StructB
76+
}
77+
78+
func fill() {
79+
a := StructA{} //@refactorrewrite("}", "Fill struct")
80+
b := StructA2{} //@refactorrewrite("}", "Fill struct")
81+
c := StructA3{
82+
B: StructB{},
83+
} //@refactorrewrite("}", "Fill struct")
84+
}
85+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package fillstruct
2+
3+
type StructB struct {
4+
StructC
5+
}
6+
7+
type StructC struct {
8+
unexportedInt int
9+
}
10+
11+
func nested() {
12+
c := StructB{
13+
StructC: StructC{}, //@refactorrewrite("}", "Fill struct")
14+
}
15+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
-- fill_struct_nested_13_20 --
2+
package fillstruct
3+
4+
type StructB struct {
5+
StructC
6+
}
7+
8+
type StructC struct {
9+
unexportedInt int
10+
}
11+
12+
func nested() {
13+
c := StructB{
14+
StructC: StructC{
15+
unexportedInt: 0,
16+
}, //@refactorrewrite("}", "Fill struct")
17+
}
18+
}
19+
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package fillstruct
2+
3+
import (
4+
data "golang.org/x/tools/internal/lsp/fillstruct/data"
5+
)
6+
7+
func unexported() {
8+
a := data.A{} //@refactorrewrite("}", "Fill struct")
9+
}

0 commit comments

Comments
 (0)