Skip to content

Commit b078437

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 978e26b commit b078437

File tree

3 files changed

+138
-0
lines changed

3 files changed

+138
-0
lines changed

internal/lsp/code_action.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,11 @@ func (s *Server) codeAction(ctx context.Context, params *protocol.CodeActionPara
134134
})
135135
}
136136
}
137+
fillActions, err := source.FillStruct(ctx, snapshot, fh, params.Range)
138+
if err != nil {
139+
return nil, err
140+
}
141+
codeActions = append(codeActions, fillActions...)
137142
default:
138143
// Unsupported file kind for a code action.
139144
return nil, nil

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
@@ -69,6 +69,7 @@ func DefaultOptions() Options {
6969
protocol.SourceFixAll: true,
7070
protocol.SourceOrganizeImports: true,
7171
protocol.QuickFix: true,
72+
protocol.RefactorRewrite: true,
7273
},
7374
Mod: {
7475
protocol.SourceOrganizeImports: true,

0 commit comments

Comments
 (0)