| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
package fillstruct |
| 14 |
|
| 15 |
import ( |
| 16 |
"bytes" |
| 17 |
"fmt" |
| 18 |
"go/ast" |
| 19 |
"go/format" |
| 20 |
"go/printer" |
| 21 |
"go/token" |
| 22 |
"go/types" |
| 23 |
"slices" |
| 24 |
"strings" |
| 25 |
"unicode" |
| 26 |
|
| 27 |
"golang.org/x/tools/go/analysis" |
| 28 |
"golang.org/x/tools/go/ast/inspector" |
| 29 |
"golang.org/x/tools/gopls/internal/analysis/fillreturns" |
| 30 |
"golang.org/x/tools/gopls/internal/cache" |
| 31 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 32 |
"golang.org/x/tools/gopls/internal/fuzzy" |
| 33 |
"golang.org/x/tools/gopls/internal/util/cursorutil" |
| 34 |
"golang.org/x/tools/gopls/internal/util/safetoken" |
| 35 |
"golang.org/x/tools/internal/astutil" |
| 36 |
"golang.org/x/tools/internal/typeparams" |
| 37 |
"golang.org/x/tools/internal/typesinternal" |
| 38 |
"golang.org/x/tools/internal/versions" |
| 39 |
) |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
func Diagnose(curFile inspector.Cursor, start, end token.Pos, pkg *types.Package, info *types.Info) (diags []analysis.Diagnostic) { |
| 49 |
cur, _, _, _ := astutil.Select(curFile, start, end) |
| 50 |
|
| 51 |
|
| 52 |
var supportsEmbedFields bool |
| 53 |
if v := info.FileVersions[curFile.Node().(*ast.File)]; v != "" { |
| 54 |
supportsEmbedFields = versions.AtLeast(v, versions.Go1_27) |
| 55 |
} |
| 56 |
|
| 57 |
var lits []*ast.CompositeLit |
| 58 |
for c := range cur.Enclosing((*ast.CompositeLit)(nil)) { |
| 59 |
lits = append(lits, c.Node().(*ast.CompositeLit)) |
| 60 |
} |
| 61 |
for c := range cur.Preorder((*ast.CompositeLit)(nil)) { |
| 62 |
expr := c.Node().(*ast.CompositeLit) |
| 63 |
|
| 64 |
if expr == cur.Node() { |
| 65 |
continue |
| 66 |
} |
| 67 |
if expr.Pos() <= end && expr.End() >= start { |
| 68 |
lits = append(lits, expr) |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
nextComp: |
| 73 |
for _, expr := range lits { |
| 74 |
typ := info.TypeOf(expr) |
| 75 |
if typ == nil { |
| 76 |
continue |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
typ = typeparams.Deref(typ) |
| 81 |
tStruct, ok := typeparams.CoreType(typ).(*types.Struct) |
| 82 |
if !ok { |
| 83 |
continue |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
fillableFields := func(t *types.Struct) (count int) { |
| 91 |
for field := range t.Fields() { |
| 92 |
if field.Pkg() == pkg || field.Exported() { |
| 93 |
count++ |
| 94 |
} |
| 95 |
} |
| 96 |
return count |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
─ A1 |
| 107 |
─ A2 |
| 108 |
edded) |
| 109 |
to A) |
| 110 |
─ B2 |
| 111 |
edded) |
| 112 |
─ C1 |
| 113 |
─ C2 |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
fieldCount := fillableFields(tStruct) |
| 123 |
|
| 124 |
var seen map[*types.Var]bool |
| 125 |
|
| 126 |
nextElem: |
| 127 |
for _, el := range expr.Elts { |
| 128 |
kv, ok := el.(*ast.KeyValueExpr) |
| 129 |
if !ok { |
| 130 |
continue nextComp |
| 131 |
} |
| 132 |
|
| 133 |
key, ok := kv.Key.(*ast.Ident) |
| 134 |
if !ok { |
| 135 |
continue |
| 136 |
} |
| 137 |
|
| 138 |
seln, ok := types.LookupSelection(typ, true, pkg, key.Name) |
| 139 |
if !ok { |
| 140 |
continue |
| 141 |
} |
| 142 |
|
| 143 |
if len(seln.Index()) > 1 && !supportsEmbedFields { |
| 144 |
continue |
| 145 |
} |
| 146 |
|
| 147 |
length := len(seln.Index()) |
| 148 |
if length == 0 { |
| 149 |
continue |
| 150 |
} |
| 151 |
|
| 152 |
var ( |
| 153 |
fields = make([]*types.Var, length-1) |
| 154 |
typs = make([]*types.Struct, length-1) |
| 155 |
) |
| 156 |
|
| 157 |
i := 0 |
| 158 |
for field := range typesinternal.ImplicitFieldSelections(seln) { |
| 159 |
t := field.Type() |
| 160 |
ptr, isPtr := t.Underlying().(*types.Pointer) |
| 161 |
if isPtr { |
| 162 |
t = ptr.Elem() |
| 163 |
} |
| 164 |
structType, ok := t.Underlying().(*types.Struct) |
| 165 |
if !ok { |
| 166 |
continue nextElem |
| 167 |
} |
| 168 |
|
| 169 |
fields[i] = field |
| 170 |
typs[i] = structType |
| 171 |
i++ |
| 172 |
} |
| 173 |
|
| 174 |
for i, field := range fields { |
| 175 |
if !seen[field] { |
| 176 |
if seen == nil { |
| 177 |
seen = make(map[*types.Var]bool) |
| 178 |
} |
| 179 |
seen[field] = true |
| 180 |
fieldCount += fillableFields(typs[i]) - 1 |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
|
| 186 |
if fieldCount == 0 || fieldCount == len(expr.Elts) { |
| 187 |
continue |
| 188 |
} |
| 189 |
|
| 190 |
|
| 191 |
var name string |
| 192 |
if typ != tStruct { |
| 193 |
|
| 194 |
name = types.TypeString(typ, typesinternal.NameRelativeTo(pkg)) |
| 195 |
} else { |
| 196 |
|
| 197 |
var buf strings.Builder |
| 198 |
buf.WriteString("anonymous struct{ ") |
| 199 |
|
| 200 |
var printedCount int |
| 201 |
|
| 202 |
for field := range tStruct.Fields() { |
| 203 |
if field.Pkg() == pkg || field.Exported() { |
| 204 |
if buf.Len() > 38 || printedCount > 3 { |
| 205 |
buf.WriteString("...") |
| 206 |
break |
| 207 |
} |
| 208 |
fmt.Fprintf(&buf, "%s: %s; ", field.Name(), field.Type().String()) |
| 209 |
printedCount++ |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
buf.WriteString(" }") |
| 214 |
name = buf.String() |
| 215 |
} |
| 216 |
|
| 217 |
diags = append(diags, analysis.Diagnostic{ |
| 218 |
Message: fmt.Sprintf("%s literal has missing fields", name), |
| 219 |
Pos: expr.Pos(), |
| 220 |
End: expr.End(), |
| 221 |
Category: FixCategory, |
| 222 |
SuggestedFixes: []analysis.SuggestedFix{{ |
| 223 |
Message: fmt.Sprintf("Fill %s", name), |
| 224 |
|
| 225 |
}}, |
| 226 |
}) |
| 227 |
} |
| 228 |
|
| 229 |
return diags |
| 230 |
} |
| 231 |
|
| 232 |
const FixCategory = "fillstruct" |
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
func SuggestedFix(cpkg *cache.Package, pgf *parsego.File, start, end token.Pos) (*token.FileSet, *analysis.SuggestedFix, error) { |
| 237 |
var ( |
| 238 |
file = pgf.File |
| 239 |
fset = cpkg.FileSet() |
| 240 |
pkg = cpkg.Types() |
| 241 |
info = cpkg.TypesInfo() |
| 242 |
pos = start |
| 243 |
) |
| 244 |
cur, ok := pgf.Cursor().FindByPos(pos, pos) |
| 245 |
if !ok { |
| 246 |
return nil, nil, fmt.Errorf("no enclosing ast.Node") |
| 247 |
} |
| 248 |
expr, _ := cursorutil.FirstEnclosing[*ast.CompositeLit](cur) |
| 249 |
|
| 250 |
|
| 251 |
newElts, err := populateMissingFields(info, pkg, file, expr, pos) |
| 252 |
if err != nil { |
| 253 |
return nil, nil, err |
| 254 |
} |
| 255 |
|
| 256 |
|
| 257 |
if len(newElts) == 0 { |
| 258 |
return nil, nil, fmt.Errorf("no elements to fill") |
| 259 |
} |
| 260 |
|
| 261 |
|
| 262 |
split := bytes.Split(pgf.Src, []byte("\n")) |
| 263 |
lineNumber := safetoken.StartPosition(fset, expr.Lbrace).Line |
| 264 |
firstLine := split[lineNumber-1] |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
trimmed := bytes.TrimLeftFunc(firstLine, unicode.IsSpace) |
| 269 |
index := bytes.Index(firstLine, trimmed) |
| 270 |
whitespace := firstLine[:index] |
| 271 |
|
| 272 |
var buf bytes.Buffer |
| 273 |
buf.WriteString("_{\n") |
| 274 |
fcmap := ast.NewCommentMap(fset, file, file.Comments) |
| 275 |
comments := fcmap.Filter(expr).Comments() |
| 276 |
for _, elt := range slices.Concat(expr.Elts, newElts) { |
| 277 |
|
| 278 |
for len(comments) > 0 && comments[0].Pos() < elt.Pos() { |
| 279 |
for _, co := range comments[0].List { |
| 280 |
fmt.Fprintln(&buf, co.Text) |
| 281 |
} |
| 282 |
comments = comments[1:] |
| 283 |
} |
| 284 |
|
| 285 |
|
| 286 |
eltcomments := fcmap.Filter(elt).Comments() |
| 287 |
if err := format.Node(&buf, fset, &printer.CommentedNode{Node: elt, Comments: eltcomments}); err != nil { |
| 288 |
return nil, nil, err |
| 289 |
} |
| 290 |
buf.WriteString(",") |
| 291 |
|
| 292 |
|
| 293 |
for len(comments) > 0 && comments[0].Pos() < elt.End() { |
| 294 |
comments = comments[1:] |
| 295 |
} |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
for _, cg := range eltcomments { |
| 300 |
for _, co := range cg.List { |
| 301 |
if co.Pos() >= elt.End() { |
| 302 |
fmt.Fprintln(&buf, co.Text) |
| 303 |
if len(comments) > 0 { |
| 304 |
comments = comments[1:] |
| 305 |
} |
| 306 |
} |
| 307 |
} |
| 308 |
} |
| 309 |
buf.WriteString("\n") |
| 310 |
} |
| 311 |
buf.WriteString("}") |
| 312 |
formatted, err := format.Source(buf.Bytes()) |
| 313 |
if err != nil { |
| 314 |
return nil, nil, err |
| 315 |
} |
| 316 |
|
| 317 |
sug := indent(formatted, whitespace) |
| 318 |
|
| 319 |
idx := bytes.IndexByte(sug, '{') |
| 320 |
sug = sug[idx:] |
| 321 |
|
| 322 |
return fset, &analysis.SuggestedFix{ |
| 323 |
TextEdits: []analysis.TextEdit{ |
| 324 |
{ |
| 325 |
Pos: expr.Lbrace, |
| 326 |
End: expr.Rbrace + token.Pos(len("}")), |
| 327 |
NewText: sug, |
| 328 |
}, |
| 329 |
}, |
| 330 |
}, nil |
| 331 |
} |
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
func populateMissingFields(info *types.Info, pkg *types.Package, file *ast.File, expr *ast.CompositeLit, pos token.Pos) ([]ast.Expr, error) { |
| 342 |
typ := info.TypeOf(expr) |
| 343 |
if typ == nil { |
| 344 |
return nil, fmt.Errorf("no composite literal") |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
typ = typeparams.Deref(typ) |
| 349 |
tStruct, ok := typ.Underlying().(*types.Struct) |
| 350 |
if !ok { |
| 351 |
return nil, fmt.Errorf("%s is not a (pointer to) struct type", |
| 352 |
types.TypeString(typ, typesinternal.NameRelativeTo(pkg))) |
| 353 |
} |
| 354 |
|
| 355 |
|
| 356 |
|
| 357 |
|
| 358 |
var supportsEmbedFields bool |
| 359 |
if v := info.FileVersions[file]; v != "" { |
| 360 |
supportsEmbedFields = versions.AtLeast(v, versions.Go1_27) |
| 361 |
} |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
explicit := make(map[*types.Var]bool) |
| 368 |
for _, elem := range expr.Elts { |
| 369 |
kv, ok := elem.(*ast.KeyValueExpr) |
| 370 |
if !ok { |
| 371 |
return nil, fmt.Errorf("cannot fill struct literal containing unkeyed elements") |
| 372 |
} |
| 373 |
|
| 374 |
key, ok := kv.Key.(*ast.Ident) |
| 375 |
if !ok { |
| 376 |
continue |
| 377 |
} |
| 378 |
|
| 379 |
seln, ok := types.LookupSelection(tStruct, true, pkg, key.Name) |
| 380 |
if !ok { |
| 381 |
continue |
| 382 |
} |
| 383 |
|
| 384 |
if len(seln.Index()) > 1 && !supportsEmbedFields { |
| 385 |
continue |
| 386 |
} |
| 387 |
|
| 388 |
field, ok := seln.Obj().(*types.Var) |
| 389 |
if !ok { |
| 390 |
continue |
| 391 |
} |
| 392 |
|
| 393 |
isExplicit, ok := explicit[field] |
| 394 |
if ok && !isExplicit { |
| 395 |
return nil, fmt.Errorf("cannot fill both %q and its subfields", field.Name()) |
| 396 |
} |
| 397 |
explicit[field] = true |
| 398 |
|
| 399 |
for field := range typesinternal.ImplicitFieldSelections(seln) { |
| 400 |
if explicit[field] { |
| 401 |
return nil, fmt.Errorf("cannot fill both %q and its subfields", field.Name()) |
| 402 |
} |
| 403 |
explicit[field] = false |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
var fields []*types.Var |
| 411 |
{ |
| 412 |
var addFields func(*types.Struct) |
| 413 |
addFields = func(tStruct *types.Struct) { |
| 414 |
for field := range tStruct.Fields() { |
| 415 |
if field.Pkg() != pkg && !field.Exported() { |
| 416 |
continue |
| 417 |
} |
| 418 |
|
| 419 |
isExplicit, ok := explicit[field] |
| 420 |
if !ok { |
| 421 |
fields = append(fields, field) |
| 422 |
continue |
| 423 |
} |
| 424 |
|
| 425 |
if !isExplicit { |
| 426 |
tInner, ok := typeparams.Deref(field.Type()).Underlying().(*types.Struct) |
| 427 |
if !ok { |
| 428 |
continue |
| 429 |
} |
| 430 |
addFields(tInner) |
| 431 |
} |
| 432 |
} |
| 433 |
} |
| 434 |
addFields(tStruct) |
| 435 |
} |
| 436 |
|
| 437 |
typs := make([]types.Type, len(fields)) |
| 438 |
for i, f := range fields { |
| 439 |
typs[i] = f.Type() |
| 440 |
} |
| 441 |
|
| 442 |
var newElts []ast.Expr |
| 443 |
matches := fillreturns.MatchingIdents(typs, file, pos, info, pkg) |
| 444 |
qual := typesinternal.FileQualifier(file, pkg) |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
for _, field := range fields { |
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
if obj, _, _ := types.LookupFieldOrMethod(tStruct, true, pkg, field.Name()); obj != field { |
| 453 |
return nil, fmt.Errorf("field %s shadowed", field.Name()) |
| 454 |
} |
| 455 |
|
| 456 |
kv := &ast.KeyValueExpr{ |
| 457 |
Key: ast.NewIdent(field.Name()), |
| 458 |
} |
| 459 |
|
| 460 |
names, ok := matches[field.Type()] |
| 461 |
if !ok { |
| 462 |
return nil, fmt.Errorf("invalid struct field type: %v", field.Type()) |
| 463 |
} |
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
if best := fuzzy.BestMatch(field.Name(), names); best != "" { |
| 469 |
kv.Value = ast.NewIdent(best) |
| 470 |
} else if expr, isValid := populateValue(field.Type(), qual); isValid { |
| 471 |
kv.Value = expr |
| 472 |
} else { |
| 473 |
continue |
| 474 |
} |
| 475 |
|
| 476 |
newElts = append(newElts, kv) |
| 477 |
} |
| 478 |
return newElts, nil |
| 479 |
} |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
func indent(str, ind []byte) []byte { |
| 484 |
split := bytes.Split(str, []byte("\n")) |
| 485 |
newText := bytes.NewBuffer(nil) |
| 486 |
for i, s := range split { |
| 487 |
if len(s) == 0 { |
| 488 |
continue |
| 489 |
} |
| 490 |
|
| 491 |
if i != 0 { |
| 492 |
newText.Write(ind) |
| 493 |
} |
| 494 |
newText.Write(s) |
| 495 |
if i < len(split)-1 { |
| 496 |
newText.WriteByte('\n') |
| 497 |
} |
| 498 |
} |
| 499 |
return newText.Bytes() |
| 500 |
} |
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
func populateValue(typ types.Type, qual types.Qualifier) (_ ast.Expr, isValid bool) { |
| 514 |
switch t := typ.(type) { |
| 515 |
case *types.TypeParam, *types.Interface, *types.Struct, *types.Basic: |
| 516 |
return typesinternal.ZeroExpr(t, qual) |
| 517 |
|
| 518 |
case *types.Alias, *types.Named: |
| 519 |
switch t.Underlying().(type) { |
| 520 |
|
| 521 |
case *types.Map, *types.Slice: |
| 522 |
return &ast.CompositeLit{ |
| 523 |
Type: typesinternal.TypeExpr(t, qual), |
| 524 |
}, true |
| 525 |
default: |
| 526 |
return typesinternal.ZeroExpr(t, qual) |
| 527 |
} |
| 528 |
|
| 529 |
|
| 530 |
case *types.Map, *types.Slice: |
| 531 |
return &ast.CompositeLit{ |
| 532 |
Type: typesinternal.TypeExpr(t, qual), |
| 533 |
}, true |
| 534 |
|
| 535 |
case *types.Array: |
| 536 |
return &ast.CompositeLit{ |
| 537 |
Type: &ast.ArrayType{ |
| 538 |
Elt: typesinternal.TypeExpr(t.Elem(), qual), |
| 539 |
Len: &ast.BasicLit{ |
| 540 |
Kind: token.INT, Value: fmt.Sprintf("%v", t.Len()), |
| 541 |
}, |
| 542 |
}, |
| 543 |
}, true |
| 544 |
|
| 545 |
case *types.Chan: |
| 546 |
dir := ast.ChanDir(t.Dir()) |
| 547 |
if t.Dir() == types.SendRecv { |
| 548 |
dir = ast.SEND | ast.RECV |
| 549 |
} |
| 550 |
return &ast.CallExpr{ |
| 551 |
Fun: ast.NewIdent("make"), |
| 552 |
Args: []ast.Expr{ |
| 553 |
&ast.ChanType{ |
| 554 |
Dir: dir, |
| 555 |
Value: typesinternal.TypeExpr(t.Elem(), qual), |
| 556 |
}, |
| 557 |
}, |
| 558 |
}, true |
| 559 |
|
| 560 |
case *types.Signature: |
| 561 |
return &ast.FuncLit{ |
| 562 |
Type: typesinternal.TypeExpr(t, qual).(*ast.FuncType), |
| 563 |
|
| 564 |
|
| 565 |
Body: &ast.BlockStmt{ |
| 566 |
List: []ast.Stmt{ |
| 567 |
&ast.ExprStmt{ |
| 568 |
X: &ast.CallExpr{ |
| 569 |
Fun: ast.NewIdent("panic"), |
| 570 |
Args: []ast.Expr{ |
| 571 |
&ast.BasicLit{ |
| 572 |
Kind: token.STRING, |
| 573 |
Value: `"TODO"`, |
| 574 |
}, |
| 575 |
}, |
| 576 |
}, |
| 577 |
}, |
| 578 |
}, |
| 579 |
}, |
| 580 |
}, true |
| 581 |
|
| 582 |
case *types.Pointer: |
| 583 |
switch tt := types.Unalias(t.Elem()).(type) { |
| 584 |
case *types.Basic: |
| 585 |
return &ast.CallExpr{ |
| 586 |
Fun: &ast.Ident{ |
| 587 |
Name: "new", |
| 588 |
}, |
| 589 |
Args: []ast.Expr{ |
| 590 |
&ast.Ident{ |
| 591 |
Name: t.Elem().String(), |
| 592 |
}, |
| 593 |
}, |
| 594 |
}, true |
| 595 |
|
| 596 |
case *types.TypeParam: |
| 597 |
return &ast.CallExpr{ |
| 598 |
Fun: &ast.Ident{ |
| 599 |
Name: "new", |
| 600 |
}, |
| 601 |
Args: []ast.Expr{ |
| 602 |
&ast.Ident{ |
| 603 |
Name: tt.Obj().Name(), |
| 604 |
}, |
| 605 |
}, |
| 606 |
}, true |
| 607 |
default: |
| 608 |
|
| 609 |
|
| 610 |
expr, isValid := populateValue(t.Elem(), qual) |
| 611 |
return &ast.UnaryExpr{ |
| 612 |
Op: token.AND, |
| 613 |
X: expr, |
| 614 |
}, isValid |
| 615 |
} |
| 616 |
} |
| 617 |
return nil, false |
| 618 |
} |