Skip to content

Commit c6b1485

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 44a64ad commit c6b1485

File tree

3 files changed

+170
-0
lines changed

3 files changed

+170
-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.StructFill(ctx, params, snapshot, fh)
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: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
// Copyright 2019 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/types"
11+
12+
"golang.org/x/tools/go/ast/astutil"
13+
"golang.org/x/tools/internal/lsp/protocol"
14+
"golang.org/x/tools/internal/lsp/snippet"
15+
)
16+
17+
func typeDefaultValues(field *types.Var, fieldType types.Type, qff types.Qualifier) string {
18+
var edit string
19+
switch typ := fieldType.(type) {
20+
case *types.Basic:
21+
switch typ.Info() {
22+
case types.IsInteger, types.IsUnsigned:
23+
edit = "0"
24+
case types.IsBoolean:
25+
edit = "false"
26+
case types.IsFloat:
27+
edit = "0.0"
28+
case types.IsString:
29+
edit = `""`
30+
}
31+
case *types.Named:
32+
switch underlying := typ.Underlying().(type) {
33+
34+
// To prevent such cases where
35+
// type NameA struct{}
36+
// type NameB NameA
37+
// type NameC NameB
38+
// we just return the field's typename.
39+
case *types.Struct:
40+
edit = types.TypeString(field.Type(), qff) + "{}"
41+
default:
42+
// get the base type of a named type recursively.
43+
edit = typeDefaultValues(field, underlying, qff)
44+
}
45+
default:
46+
edit = "nil"
47+
}
48+
return edit
49+
}
50+
51+
func StructFill(ctx context.Context, params *protocol.CodeActionParams, snapshot Snapshot, fh FileHandle) ([]protocol.CodeAction, error) {
52+
rangeOfTarget := params.Range
53+
54+
pkg, pgh, err := getParsedFile(ctx, snapshot, fh, NarrowestPackageHandle)
55+
if err != nil {
56+
return nil, fmt.Errorf("getting file for Completion: %v", err)
57+
}
58+
file, _, m, _, err := pgh.Cached()
59+
if err != nil {
60+
return nil, err
61+
}
62+
spn, err := m.PointSpan(rangeOfTarget.Start)
63+
if err != nil {
64+
return nil, err
65+
}
66+
rng, err := spn.Range(m.Converter)
67+
if err != nil {
68+
return nil, err
69+
}
70+
path, _ := astutil.PathEnclosingInterval(file, rng.Start, rng.End)
71+
if path == nil {
72+
return nil, nil
73+
}
74+
75+
ecl := enclosingCompositeLiteral(path, rng.Start, pkg.GetTypesInfo())
76+
if ecl == nil || !ecl.isStruct() {
77+
return nil, nil
78+
}
79+
80+
// If in F{ Bar<> : V} or anywhere in F{Bar : V, ...}
81+
// we should not fill the struct.
82+
if ecl.inKey || len(ecl.cl.Elts) != 0 {
83+
return nil, nil
84+
}
85+
86+
// the range to replace all text between enclosing braces {<> ... <>}
87+
newMappedRange := newMappedRange(snapshot.View().Session().Cache().FileSet(), m, ecl.cl.Lbrace+1, ecl.cl.Rbrace)
88+
newProtoRange, err := newMappedRange.Range()
89+
if err != nil {
90+
return nil, err
91+
}
92+
93+
var codeActions []protocol.CodeAction
94+
qfFunc := qualifier(file, pkg.GetTypes(), pkg.GetTypesInfo())
95+
switch obj := ecl.clType.(type) {
96+
case *types.Struct:
97+
98+
fieldCount := obj.NumFields()
99+
if fieldCount == 0 {
100+
return codeActions, nil
101+
}
102+
var edit, insert string
103+
for i := 0; i < fieldCount; i++ {
104+
field := obj.Field(i)
105+
// Ignore fields that are not accessible in the current package.
106+
if field.Pkg() != nil && field.Pkg() != pkg.GetTypes() && !field.Exported() {
107+
continue
108+
}
109+
110+
// Code action does not support placeholders (?) yet
111+
_, insert = generateCompletionForStructFields(&snippet.Builder{}, field, qfFunc, false)
112+
edit += insert
113+
}
114+
edit += "\n"
115+
codeActions = append(codeActions, protocol.CodeAction{
116+
Title: "Fill struct",
117+
Kind: protocol.RefactorRewrite,
118+
Edit: protocol.WorkspaceEdit{
119+
DocumentChanges: []protocol.TextDocumentEdit{
120+
{
121+
TextDocument: protocol.VersionedTextDocumentIdentifier{
122+
Version: fh.Identity().Version,
123+
TextDocumentIdentifier: protocol.TextDocumentIdentifier{
124+
URI: protocol.URIFromSpanURI(fh.Identity().URI),
125+
},
126+
},
127+
Edits: []protocol.TextEdit{
128+
{
129+
Range: newProtoRange,
130+
NewText: edit,
131+
},
132+
},
133+
},
134+
},
135+
},
136+
})
137+
}
138+
139+
return codeActions, nil
140+
}
141+
142+
func generateCompletionForStructFields(snip *snippet.Builder, field *types.Var, qualifer types.Qualifier, placeholder bool) (*snippet.Builder, string) {
143+
var (
144+
label = field.Name()
145+
detail = typeDefaultValues(field, field.Type(), qualifer)
146+
text = "\n" + label + " : " + detail + ","
147+
)
148+
149+
// A plain snippet turns "Foo{Ba<>" into "Foo{Bar: <>".
150+
snip.WriteText("\n" + label + ": ")
151+
152+
// Don't write placeholders if it is not offered.
153+
if placeholder {
154+
snip.WritePlaceholder(func(b *snippet.Builder) {
155+
// A placeholder snippet turns "Foo{Ba<>" into "Foo{Bar: <*int*>".
156+
b.WriteText(detail)
157+
})
158+
} else {
159+
snip.WriteText(detail)
160+
}
161+
162+
snip.WriteText(",")
163+
return snip, text
164+
}

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)