@@ -198,23 +198,23 @@ func insertStructField(ctx context.Context, snapshot *cache.Snapshot, mp *metada
198
198
}
199
199
200
200
// find the struct type declaration
201
- var structType * ast.StructType
202
- ast .Inspect (declPGF .File , func (n ast.Node ) bool {
203
- if typeSpec , ok := n .(* ast.TypeSpec ); ok {
204
- if typeSpec .Name .Name == fieldInfo .Named .Obj ().Name () {
205
- if st , ok := typeSpec .Type .(* ast.StructType ); ok {
206
- structType = st
207
- return false
208
- }
209
- }
210
- }
211
- return true
212
- })
201
+ pos := fieldInfo .Named .Obj ().Pos ()
202
+ endPos := pos + token .Pos (len (fieldInfo .Named .Obj ().Name ()))
203
+ curIdent , ok := declPGF .Cursor .FindPos (pos , endPos )
204
+ if ! ok {
205
+ return nil , nil , fmt .Errorf ("could not find identifier at position %v-%v" , pos , endPos )
206
+ }
213
207
214
- if structType == nil {
215
- return nil , nil , fmt .Errorf ("could not find struct definition" )
208
+ // Rest of the code remains the same
209
+ typeNode , ok := curIdent .NextSibling ()
210
+ if ! ok {
211
+ return nil , nil , fmt .Errorf ("could not find type specification" )
216
212
}
217
213
214
+ structType , ok := typeNode .Node ().(* ast.StructType )
215
+ if ! ok {
216
+ return nil , nil , fmt .Errorf ("type at position %v is not a struct type" , pos )
217
+ }
218
218
// Find metadata for the symbol's declaring package
219
219
// as we'll need its import mapping.
220
220
declMeta := findFileInDeps (snapshot , mp , declPGF .URI )
@@ -229,27 +229,24 @@ func insertStructField(ctx context.Context, snapshot *cache.Snapshot, mp *metada
229
229
if insertPos == structType .Fields .Opening {
230
230
// struct has no fields yet
231
231
insertPos = structType .Fields .Closing
232
+ _ , err = declPGF .Mapper .PosRange (declPGF .Tok , insertPos , insertPos )
233
+ if err != nil {
234
+ return nil , nil , err
235
+ }
232
236
}
233
237
234
238
var buf bytes.Buffer
235
239
if err := fieldInfo .Emit (& buf , qual ); err != nil {
236
240
return nil , nil , err
237
241
}
238
242
239
- _ , err = declPGF .Mapper .PosRange (declPGF .Tok , insertPos , insertPos )
240
- if err != nil {
241
- return nil , nil , err
242
- }
243
-
244
- textEdit := analysis.TextEdit {
245
- Pos : insertPos ,
246
- End : insertPos ,
247
- NewText : buf .Bytes (),
248
- }
249
-
250
243
return fieldInfo .Fset , & analysis.SuggestedFix {
251
- Message : fmt .Sprintf ("Add field %s to struct %s" , fieldInfo .Expr .Sel .Name , fieldInfo .Named .Obj ().Name ()),
252
- TextEdits : []analysis.TextEdit {textEdit },
244
+ Message : fmt .Sprintf ("Add field %s to struct %s" , fieldInfo .Expr .Sel .Name , fieldInfo .Named .Obj ().Name ()),
245
+ TextEdits : []analysis.TextEdit {{
246
+ Pos : insertPos ,
247
+ End : insertPos ,
248
+ NewText : buf .Bytes (),
249
+ }},
253
250
}, nil
254
251
}
255
252
0 commit comments