| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package cache |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"cmp" |
| 10 |
"context" |
| 11 |
"errors" |
| 12 |
"fmt" |
| 13 |
"go/ast" |
| 14 |
"go/build/constraint" |
| 15 |
"go/parser" |
| 16 |
"go/token" |
| 17 |
"os" |
| 18 |
"path" |
| 19 |
"path/filepath" |
| 20 |
"regexp" |
| 21 |
"slices" |
| 22 |
"strconv" |
| 23 |
"strings" |
| 24 |
"sync" |
| 25 |
|
| 26 |
"golang.org/x/tools/go/types/objectpath" |
| 27 |
"golang.org/x/tools/gopls/internal/cache/metadata" |
| 28 |
"golang.org/x/tools/gopls/internal/cache/methodsets" |
| 29 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 30 |
"golang.org/x/tools/gopls/internal/cache/testfuncs" |
| 31 |
"golang.org/x/tools/gopls/internal/cache/xrefs" |
| 32 |
"golang.org/x/tools/gopls/internal/file" |
| 33 |
"golang.org/x/tools/gopls/internal/filecache" |
| 34 |
label1 "golang.org/x/tools/gopls/internal/label" |
| 35 |
"golang.org/x/tools/gopls/internal/protocol" |
| 36 |
"golang.org/x/tools/gopls/internal/protocol/command" |
| 37 |
"golang.org/x/tools/gopls/internal/settings" |
| 38 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 39 |
"golang.org/x/tools/gopls/internal/util/constraints" |
| 40 |
"golang.org/x/tools/gopls/internal/util/immutable" |
| 41 |
"golang.org/x/tools/gopls/internal/util/memoize" |
| 42 |
"golang.org/x/tools/gopls/internal/util/moremaps" |
| 43 |
"golang.org/x/tools/gopls/internal/util/pathutil" |
| 44 |
"golang.org/x/tools/gopls/internal/util/persistent" |
| 45 |
"golang.org/x/tools/gopls/internal/vulncheck" |
| 46 |
"golang.org/x/tools/internal/event" |
| 47 |
"golang.org/x/tools/internal/event/label" |
| 48 |
"golang.org/x/tools/internal/gocommand" |
| 49 |
) |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
type Snapshot struct { |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
sequenceID uint64 |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
view *View |
| 77 |
|
| 78 |
cancel func() |
| 79 |
backgroundCtx context.Context |
| 80 |
|
| 81 |
store *memoize.Store |
| 82 |
|
| 83 |
refMu sync.Mutex |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
refcount int |
| 91 |
done func() |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
mu sync.Mutex |
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
initialized bool |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
initialErr *InitializationError |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
builtin protocol.DocumentURI |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
meta *metadata.Graph |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
files *fileMap |
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
packages *persistent.Map[PackageID, *packageHandle] |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
fullAnalysisKeys *persistent.Map[PackageID, file.Hash] |
| 146 |
factyAnalysisKeys *persistent.Map[PackageID, file.Hash] |
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
workspacePackages immutable.Map[PackageID, PackagePath] |
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
shouldLoad *persistent.Map[PackageID, []PackagePath] |
| 158 |
|
| 159 |
|
| 160 |
unloadableFiles *persistent.Set[protocol.DocumentURI] |
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
parseModHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] |
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
parseWorkHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] |
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
modTidyHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] |
| 177 |
modWhyHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] |
| 178 |
modVulnHandles *persistent.Map[protocol.DocumentURI, *memoize.Promise] |
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
moduleUpgrades *persistent.Map[protocol.DocumentURI, map[string]string] |
| 183 |
|
| 184 |
|
| 185 |
vulns *persistent.Map[protocol.DocumentURI, *vulncheck.Result] |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
compilerOptDetails map[protocol.DocumentURI]unit |
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
typeCheckMu sync.Mutex |
| 196 |
batchRef int |
| 197 |
batch *typeCheckBatch |
| 198 |
} |
| 199 |
|
| 200 |
var _ memoize.RefCounted = (*Snapshot)(nil) |
| 201 |
|
| 202 |
func (s *Snapshot) awaitPromise(ctx context.Context, p *memoize.Promise) (any, error) { |
| 203 |
return p.Get(ctx, s) |
| 204 |
} |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
func (s *Snapshot) Acquire() func() { |
| 217 |
s.refMu.Lock() |
| 218 |
defer s.refMu.Unlock() |
| 219 |
assert(s.refcount > 0, "non-positive refs") |
| 220 |
s.refcount++ |
| 221 |
|
| 222 |
return s.decref |
| 223 |
} |
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
func (s *Snapshot) decref() { |
| 228 |
s.refMu.Lock() |
| 229 |
defer s.refMu.Unlock() |
| 230 |
|
| 231 |
assert(s.refcount > 0, "non-positive refs") |
| 232 |
s.refcount-- |
| 233 |
if s.refcount == 0 { |
| 234 |
s.packages.Destroy() |
| 235 |
s.files.destroy() |
| 236 |
s.parseModHandles.Destroy() |
| 237 |
s.parseWorkHandles.Destroy() |
| 238 |
s.modTidyHandles.Destroy() |
| 239 |
s.modVulnHandles.Destroy() |
| 240 |
s.modWhyHandles.Destroy() |
| 241 |
s.unloadableFiles.Destroy() |
| 242 |
s.moduleUpgrades.Destroy() |
| 243 |
s.vulns.Destroy() |
| 244 |
s.done() |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
func (s *Snapshot) SequenceID() uint64 { |
| 255 |
return s.sequenceID |
| 256 |
} |
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
func (s *Snapshot) Labels() []label.Label { |
| 261 |
return []label.Label{ |
| 262 |
label1.ViewID.Of(s.view.id), |
| 263 |
label1.Snapshot.Of(s.SequenceID()), |
| 264 |
label1.Directory.Of(s.Folder().Path()), |
| 265 |
} |
| 266 |
} |
| 267 |
|
| 268 |
|
| 269 |
func (s *Snapshot) Folder() protocol.DocumentURI { |
| 270 |
return s.view.folder.Dir |
| 271 |
} |
| 272 |
|
| 273 |
|
| 274 |
func (s *Snapshot) View() *View { |
| 275 |
return s.view |
| 276 |
} |
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
func (s *Snapshot) FileKind(fh file.Handle) file.Kind { |
| 286 |
if k := fileKind(fh); k != file.UnknownKind { |
| 287 |
return k |
| 288 |
} |
| 289 |
fext := filepath.Ext(fh.URI().Path()) |
| 290 |
exts := s.Options().TemplateExtensions |
| 291 |
for _, ext := range exts { |
| 292 |
if fext == ext || fext == "."+ext { |
| 293 |
return file.Tmpl |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
return file.Go |
| 303 |
} |
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
func fileKind(fh file.Handle) file.Kind { |
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
if o, ok := fh.(*overlay); ok { |
| 312 |
if o.kind != file.UnknownKind { |
| 313 |
return o.kind |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
fext := filepath.Ext(fh.URI().Path()) |
| 318 |
switch fext { |
| 319 |
case ".go": |
| 320 |
return file.Go |
| 321 |
case ".mod": |
| 322 |
return file.Mod |
| 323 |
case ".sum": |
| 324 |
return file.Sum |
| 325 |
case ".work": |
| 326 |
return file.Work |
| 327 |
case ".s": |
| 328 |
return file.Asm |
| 329 |
} |
| 330 |
return file.UnknownKind |
| 331 |
} |
| 332 |
|
| 333 |
|
| 334 |
func (s *Snapshot) Options() *settings.Options { |
| 335 |
return s.view.folder.Options |
| 336 |
} |
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
func (s *Snapshot) BackgroundContext() context.Context { |
| 341 |
return s.backgroundCtx |
| 342 |
} |
| 343 |
|
| 344 |
|
| 345 |
func (s *Snapshot) Templates() map[protocol.DocumentURI]file.Handle { |
| 346 |
s.mu.Lock() |
| 347 |
defer s.mu.Unlock() |
| 348 |
|
| 349 |
tmpls := map[protocol.DocumentURI]file.Handle{} |
| 350 |
for k, fh := range s.files.all() { |
| 351 |
if s.FileKind(fh) == file.Tmpl { |
| 352 |
tmpls[k] = fh |
| 353 |
} |
| 354 |
} |
| 355 |
return tmpls |
| 356 |
} |
| 357 |
|
| 358 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
func (s *Snapshot) RunGoModUpdateCommands(ctx context.Context, modURI protocol.DocumentURI, run func(invoke func(...string) (*bytes.Buffer, error)) error) ([]byte, []byte, error) { |
| 365 |
tempDir, cleanupModDir, err := TempModDir(ctx, s, modURI) |
| 366 |
if err != nil { |
| 367 |
return nil, nil, err |
| 368 |
} |
| 369 |
defer cleanupModDir() |
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
inv, cleanupInvocation, err := s.GoCommandInvocation(NetworkOK, modURI.DirPath(), "", nil, "GOWORK=off") |
| 375 |
if err != nil { |
| 376 |
return nil, nil, err |
| 377 |
} |
| 378 |
defer cleanupInvocation() |
| 379 |
|
| 380 |
inv.ModFlag = "mod" |
| 381 |
inv.ModFile = filepath.Join(tempDir, "go.mod") |
| 382 |
invoke := func(args ...string) (*bytes.Buffer, error) { |
| 383 |
inv.Verb = args[0] |
| 384 |
inv.Args = args[1:] |
| 385 |
return s.view.gocmdRunner.Run(ctx, *inv) |
| 386 |
} |
| 387 |
if err := run(invoke); err != nil { |
| 388 |
return nil, nil, err |
| 389 |
} |
| 390 |
var modBytes, sumBytes []byte |
| 391 |
modBytes, err = os.ReadFile(filepath.Join(tempDir, "go.mod")) |
| 392 |
if err != nil && !os.IsNotExist(err) { |
| 393 |
return nil, nil, err |
| 394 |
} |
| 395 |
sumBytes, err = os.ReadFile(filepath.Join(tempDir, "go.sum")) |
| 396 |
if err != nil && !os.IsNotExist(err) { |
| 397 |
return nil, nil, err |
| 398 |
} |
| 399 |
return modBytes, sumBytes, nil |
| 400 |
} |
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
func TempModDir(ctx context.Context, fs file.Source, modURI protocol.DocumentURI) (dir string, _ func(), rerr error) { |
| 407 |
dir, err := os.MkdirTemp("", "gopls-tempmod") |
| 408 |
if err != nil { |
| 409 |
return "", nil, err |
| 410 |
} |
| 411 |
cleanup := func() { |
| 412 |
if err := os.RemoveAll(dir); err != nil { |
| 413 |
event.Error(ctx, "cleaning temp dir", err) |
| 414 |
} |
| 415 |
} |
| 416 |
defer func() { |
| 417 |
if rerr != nil { |
| 418 |
cleanup() |
| 419 |
} |
| 420 |
}() |
| 421 |
|
| 422 |
|
| 423 |
modFH, err := fs.ReadFile(ctx, modURI) |
| 424 |
if err != nil { |
| 425 |
return "", nil, err |
| 426 |
} |
| 427 |
if data, err := modFH.Content(); err == nil { |
| 428 |
if err := os.WriteFile(filepath.Join(dir, "go.mod"), data, 0666); err != nil { |
| 429 |
return "", nil, err |
| 430 |
} |
| 431 |
} |
| 432 |
|
| 433 |
|
| 434 |
sumURI := protocol.DocumentURI(strings.TrimSuffix(string(modURI), ".mod") + ".sum") |
| 435 |
sumFH, err := fs.ReadFile(ctx, sumURI) |
| 436 |
if err != nil { |
| 437 |
return "", nil, err |
| 438 |
} |
| 439 |
if data, err := sumFH.Content(); err == nil { |
| 440 |
if err := os.WriteFile(filepath.Join(dir, "go.sum"), data, 0666); err != nil { |
| 441 |
return "", nil, err |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
return dir, cleanup, nil |
| 446 |
} |
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
type AllowNetwork bool |
| 451 |
|
| 452 |
const ( |
| 453 |
NoNetwork AllowNetwork = false |
| 454 |
NetworkOK AllowNetwork = true |
| 455 |
) |
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
func (s *Snapshot) GoCommandInvocation(allowNetwork AllowNetwork, dir, verb string, args []string, env ...string) (_ *gocommand.Invocation, cleanup func(), _ error) { |
| 469 |
inv := &gocommand.Invocation{ |
| 470 |
Verb: verb, |
| 471 |
Args: args, |
| 472 |
WorkingDir: dir, |
| 473 |
Env: append(s.view.Env(), env...), |
| 474 |
BuildFlags: slices.Clone(s.Options().BuildFlags), |
| 475 |
} |
| 476 |
if !allowNetwork { |
| 477 |
inv.Env = append(inv.Env, "GOPROXY=off") |
| 478 |
} |
| 479 |
|
| 480 |
|
| 481 |
overlay, cleanup, err := gocommand.WriteOverlays(s.buildOverlays()) |
| 482 |
if err != nil { |
| 483 |
return nil, nil, err |
| 484 |
} |
| 485 |
inv.Overlay = overlay |
| 486 |
return inv, cleanup, nil |
| 487 |
} |
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
func (s *Snapshot) buildOverlays() map[string][]byte { |
| 493 |
overlays := make(map[string][]byte) |
| 494 |
for _, overlay := range s.Overlays() { |
| 495 |
if overlay.saved { |
| 496 |
continue |
| 497 |
} |
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
overlays[overlay.URI().Path()] = overlay.content |
| 502 |
} |
| 503 |
return overlays |
| 504 |
} |
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
func (s *Snapshot) Overlays() []*overlay { |
| 511 |
s.mu.Lock() |
| 512 |
defer s.mu.Unlock() |
| 513 |
|
| 514 |
return s.files.getOverlays() |
| 515 |
} |
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
const ( |
| 520 |
xrefsKind = "xrefs" |
| 521 |
methodSetsKind = "methodsets" |
| 522 |
testsKind = "tests" |
| 523 |
exportDataKind = "export" |
| 524 |
diagnosticsKind = "diagnostics" |
| 525 |
typerefsKind = "typerefs" |
| 526 |
symbolsKind = "symbols" |
| 527 |
) |
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
func (s *Snapshot) PackageDiagnostics(ctx context.Context, ids ...PackageID) (map[protocol.DocumentURI][]*Diagnostic, error) { |
| 535 |
ctx, done := event.Start(ctx, "cache.snapshot.PackageDiagnostics") |
| 536 |
defer done() |
| 537 |
|
| 538 |
var mu sync.Mutex |
| 539 |
perFile := make(map[protocol.DocumentURI][]*Diagnostic) |
| 540 |
collect := func(diags []*Diagnostic) { |
| 541 |
mu.Lock() |
| 542 |
defer mu.Unlock() |
| 543 |
for _, diag := range diags { |
| 544 |
perFile[diag.URI] = append(perFile[diag.URI], diag) |
| 545 |
} |
| 546 |
} |
| 547 |
pre := func(_ int, ph *packageHandle) bool { |
| 548 |
if diags, ok := filecache.GetOrFatal(diagnosticsKind, ph.key, decodeDiagnostics); ok { |
| 549 |
collect(ph.loadDiagnostics) |
| 550 |
collect(diags) |
| 551 |
return false |
| 552 |
} |
| 553 |
return true |
| 554 |
} |
| 555 |
post := func(_ int, pkg *Package) { |
| 556 |
collect(pkg.loadDiagnostics) |
| 557 |
collect(pkg.pkg.diagnostics) |
| 558 |
} |
| 559 |
return perFile, s.forEachPackage(ctx, ids, pre, post) |
| 560 |
} |
| 561 |
|
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
func (s *Snapshot) References(ctx context.Context, ids ...PackageID) ([]xrefIndex, error) { |
| 567 |
ctx, done := event.Start(ctx, "cache.snapshot.References") |
| 568 |
defer done() |
| 569 |
|
| 570 |
indexes := make([]xrefIndex, len(ids)) |
| 571 |
pre := func(i int, ph *packageHandle) bool { |
| 572 |
if idx, ok := filecache.GetOrFatal(xrefsKind, ph.key, xrefs.Decode); ok { |
| 573 |
indexes[i] = xrefIndex{mp: ph.mp, idx: idx} |
| 574 |
return false |
| 575 |
} |
| 576 |
return true |
| 577 |
} |
| 578 |
post := func(i int, pkg *Package) { |
| 579 |
indexes[i] = xrefIndex{mp: pkg.metadata, idx: pkg.pkg.xrefs()} |
| 580 |
} |
| 581 |
return indexes, s.forEachPackage(ctx, ids, pre, post) |
| 582 |
} |
| 583 |
|
| 584 |
|
| 585 |
type xrefIndex struct { |
| 586 |
mp *metadata.Package |
| 587 |
idx *xrefs.Index |
| 588 |
} |
| 589 |
|
| 590 |
func (index xrefIndex) Lookup(targets map[PackagePath]map[objectpath.Path]struct{}) []protocol.Location { |
| 591 |
return index.idx.Lookup(index.mp, targets) |
| 592 |
} |
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
func (s *Snapshot) MethodSets(ctx context.Context, ids ...PackageID) ([]*methodsets.Index, error) { |
| 599 |
ctx, done := event.Start(ctx, "cache.snapshot.MethodSets") |
| 600 |
defer done() |
| 601 |
|
| 602 |
indexes := make([]*methodsets.Index, len(ids)) |
| 603 |
pre := func(i int, ph *packageHandle) bool { |
| 604 |
pkgPath := ph.mp.PkgPath |
| 605 |
if idx, ok := filecache.GetOrFatal(methodSetsKind, ph.key, func(data []byte) *methodsets.Index { |
| 606 |
return methodsets.Decode(pkgPath, data) |
| 607 |
}); ok { |
| 608 |
indexes[i] = idx |
| 609 |
return false |
| 610 |
} |
| 611 |
return true |
| 612 |
} |
| 613 |
post := func(i int, pkg *Package) { |
| 614 |
indexes[i] = pkg.pkg.methodsets() |
| 615 |
} |
| 616 |
return indexes, s.forEachPackage(ctx, ids, pre, post) |
| 617 |
} |
| 618 |
|
| 619 |
|
| 620 |
|
| 621 |
|
| 622 |
|
| 623 |
|
| 624 |
func (s *Snapshot) Tests(ctx context.Context, ids ...PackageID) ([]*testfuncs.Index, error) { |
| 625 |
ctx, done := event.Start(ctx, "cache.snapshot.Tests") |
| 626 |
defer done() |
| 627 |
|
| 628 |
indexes := make([]*testfuncs.Index, len(ids)) |
| 629 |
pre := func(i int, ph *packageHandle) bool { |
| 630 |
if idx, ok := filecache.GetOrFatal(testsKind, ph.key, testfuncs.Decode); ok { |
| 631 |
indexes[i] = idx |
| 632 |
return false |
| 633 |
} |
| 634 |
return true |
| 635 |
} |
| 636 |
post := func(i int, pkg *Package) { |
| 637 |
indexes[i] = pkg.pkg.tests() |
| 638 |
} |
| 639 |
return indexes, s.forEachPackage(ctx, ids, pre, post) |
| 640 |
} |
| 641 |
|
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
func (snapshot *Snapshot) NarrowestMetadataForFile(ctx context.Context, uri protocol.DocumentURI) (*metadata.Package, error) { |
| 646 |
mps, err := snapshot.MetadataForFile(ctx, uri, true) |
| 647 |
if err != nil { |
| 648 |
return nil, err |
| 649 |
} |
| 650 |
if len(mps) == 0 { |
| 651 |
return nil, fmt.Errorf("no package metadata for file %s", uri) |
| 652 |
} |
| 653 |
return mps[0], nil |
| 654 |
} |
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
func (s *Snapshot) MetadataForFile(ctx context.Context, uri protocol.DocumentURI, removeIntermediateTestVariants bool) ([]*metadata.Package, error) { |
| 665 |
if s.view.typ == AdHocView { |
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
if err := s.awaitLoaded(ctx); err != nil { |
| 673 |
return nil, err |
| 674 |
} |
| 675 |
} |
| 676 |
|
| 677 |
s.mu.Lock() |
| 678 |
|
| 679 |
|
| 680 |
pkgs := s.meta.ForFile[uri] |
| 681 |
|
| 682 |
shouldLoad := false |
| 683 |
for _, pkg := range pkgs { |
| 684 |
if p, _ := s.shouldLoad.Get(pkg.ID); len(p) > 0 { |
| 685 |
shouldLoad = true |
| 686 |
} |
| 687 |
} |
| 688 |
|
| 689 |
|
| 690 |
unloadable := s.unloadableFiles.Contains(uri) |
| 691 |
|
| 692 |
s.mu.Unlock() |
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
|
| 698 |
if (shouldLoad || len(pkgs) == 0) && !unloadable { |
| 699 |
scope := fileLoadScope(uri) |
| 700 |
err := s.load(ctx, NoNetwork, scope) |
| 701 |
|
| 702 |
|
| 703 |
|
| 704 |
if err != nil { |
| 705 |
|
| 706 |
|
| 707 |
if ctx.Err() != nil { |
| 708 |
return nil, ctx.Err() |
| 709 |
} |
| 710 |
|
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
if !errors.Is(err, errNoPackages) { |
| 715 |
event.Error(ctx, "MetadataForFile", err) |
| 716 |
} |
| 717 |
} |
| 718 |
|
| 719 |
|
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
s.clearShouldLoad(scope) |
| 725 |
} |
| 726 |
|
| 727 |
|
| 728 |
s.mu.Lock() |
| 729 |
defer s.mu.Unlock() |
| 730 |
|
| 731 |
|
| 732 |
metas := slices.Clone(s.meta.ForFile[uri]) |
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
if !unloadable && len(metas) == 0 { |
| 738 |
s.unloadableFiles.Add(uri) |
| 739 |
} |
| 740 |
|
| 741 |
if removeIntermediateTestVariants { |
| 742 |
metadata.RemoveIntermediateTestVariants(&metas) |
| 743 |
} |
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
slices.SortFunc(metas, func(x, y *metadata.Package) int { |
| 750 |
if sign := cmp.Compare(len(x.CompiledGoFiles), len(y.CompiledGoFiles)); sign != 0 { |
| 751 |
return sign |
| 752 |
} |
| 753 |
|
| 754 |
if removeIntermediateTestVariants { |
| 755 |
return 0 |
| 756 |
} |
| 757 |
return boolCompare(x.IsIntermediateTestVariant(), y.IsIntermediateTestVariant()) |
| 758 |
}) |
| 759 |
|
| 760 |
return metas, nil |
| 761 |
} |
| 762 |
|
| 763 |
|
| 764 |
func btoi(b bool) int { |
| 765 |
if b { |
| 766 |
return 1 |
| 767 |
} else { |
| 768 |
return 0 |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
func boolCompare(x, y bool) int { |
| 775 |
return btoi(x) - btoi(y) |
| 776 |
} |
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
func (s *Snapshot) ReverseDependencies(ctx context.Context, id PackageID, transitive bool) (map[PackageID]*metadata.Package, error) { |
| 783 |
if err := s.awaitLoaded(ctx); err != nil { |
| 784 |
return nil, err |
| 785 |
} |
| 786 |
|
| 787 |
meta := s.MetadataGraph() |
| 788 |
var rdeps map[PackageID]*metadata.Package |
| 789 |
if transitive { |
| 790 |
rdeps = meta.ReverseReflexiveTransitiveClosure(id) |
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
delete(rdeps, id) |
| 796 |
|
| 797 |
} else { |
| 798 |
|
| 799 |
rdeps = make(map[PackageID]*metadata.Package) |
| 800 |
for _, rdep := range meta.ImportedBy[id] { |
| 801 |
rdeps[rdep.ID] = rdep |
| 802 |
} |
| 803 |
} |
| 804 |
|
| 805 |
return rdeps, nil |
| 806 |
} |
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
func (s *Snapshot) fileWatchingGlobPatterns() map[protocol.RelativePattern]unit { |
| 811 |
|
| 812 |
patterns := make(map[protocol.RelativePattern]unit) |
| 813 |
|
| 814 |
|
| 815 |
if s.view.gowork != "" && !s.view.folder.Dir.Encloses(s.view.gowork) { |
| 816 |
workPattern := protocol.RelativePattern{ |
| 817 |
BaseURI: s.view.gowork.Dir(), |
| 818 |
Pattern: path.Base(string(s.view.gowork)), |
| 819 |
} |
| 820 |
patterns[workPattern] = unit{} |
| 821 |
} |
| 822 |
|
| 823 |
for _, glob := range s.Options().WorkspaceFiles { |
| 824 |
patterns[protocol.RelativePattern{Pattern: glob}] = unit{} |
| 825 |
} |
| 826 |
|
| 827 |
var extensions strings.Builder |
| 828 |
extensions.WriteString("go,mod,sum,work") |
| 829 |
for _, ext := range s.Options().TemplateExtensions { |
| 830 |
extensions.WriteString(",") |
| 831 |
extensions.WriteString(ext) |
| 832 |
} |
| 833 |
watchGoFiles := fmt.Sprintf("**/*.{%s}", extensions.String()) |
| 834 |
|
| 835 |
var dirs []string |
| 836 |
if s.view.typ.usesModules() { |
| 837 |
if s.view.typ == GoWorkView { |
| 838 |
workVendorDir := filepath.Join(s.view.gowork.DirPath(), "vendor") |
| 839 |
workVendorURI := protocol.URIFromPath(workVendorDir) |
| 840 |
patterns[protocol.RelativePattern{BaseURI: workVendorURI, Pattern: watchGoFiles}] = unit{} |
| 841 |
} |
| 842 |
|
| 843 |
|
| 844 |
|
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
for modFile := range s.view.workspaceModFiles { |
| 849 |
dirs = append(dirs, modFile.DirPath()) |
| 850 |
|
| 851 |
|
| 852 |
|
| 853 |
|
| 854 |
|
| 855 |
|
| 856 |
patterns[protocol.RelativePattern{BaseURI: modFile.Dir(), Pattern: watchGoFiles}] = unit{} |
| 857 |
} |
| 858 |
} else { |
| 859 |
|
| 860 |
dirs = []string{s.view.root.Path()} |
| 861 |
patterns[protocol.RelativePattern{Pattern: watchGoFiles}] = unit{} |
| 862 |
} |
| 863 |
|
| 864 |
if s.watchSubdirs() { |
| 865 |
|
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
|
| 871 |
|
| 872 |
|
| 873 |
|
| 874 |
|
| 875 |
|
| 876 |
|
| 877 |
|
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
|
| 884 |
s.addKnownSubdirs(patterns, dirs) |
| 885 |
} |
| 886 |
|
| 887 |
return patterns |
| 888 |
} |
| 889 |
|
| 890 |
func (s *Snapshot) addKnownSubdirs(patterns map[protocol.RelativePattern]unit, wsDirs []string) { |
| 891 |
s.mu.Lock() |
| 892 |
defer s.mu.Unlock() |
| 893 |
|
| 894 |
for dir := range s.files.getDirs().All() { |
| 895 |
for _, wsDir := range wsDirs { |
| 896 |
if pathutil.InDir(wsDir, dir) { |
| 897 |
patterns[protocol.RelativePattern{Pattern: filepath.ToSlash(dir)}] = unit{} |
| 898 |
} |
| 899 |
} |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
func (s *Snapshot) watchSubdirs() bool { |
| 908 |
switch p := s.Options().SubdirWatchPatterns; p { |
| 909 |
case settings.SubdirWatchPatternsOn: |
| 910 |
return true |
| 911 |
case settings.SubdirWatchPatternsOff: |
| 912 |
return false |
| 913 |
case settings.SubdirWatchPatternsAuto: |
| 914 |
|
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
|
| 921 |
switch s.Options().ClientInfo.Name { |
| 922 |
case "Visual Studio Code", "Visual Studio Code - Insiders": |
| 923 |
return true |
| 924 |
default: |
| 925 |
return false |
| 926 |
} |
| 927 |
default: |
| 928 |
bug.Reportf("invalid subdirWatchPatterns: %q", p) |
| 929 |
return false |
| 930 |
} |
| 931 |
} |
| 932 |
|
| 933 |
|
| 934 |
|
| 935 |
func (s *Snapshot) filesInDir(uri protocol.DocumentURI) []protocol.DocumentURI { |
| 936 |
s.mu.Lock() |
| 937 |
defer s.mu.Unlock() |
| 938 |
|
| 939 |
dir := uri.Path() |
| 940 |
if !s.files.getDirs().Contains(dir) { |
| 941 |
return nil |
| 942 |
} |
| 943 |
var files []protocol.DocumentURI |
| 944 |
for uri := range s.files.all() { |
| 945 |
if pathutil.InDir(dir, uri.Path()) { |
| 946 |
files = append(files, uri) |
| 947 |
} |
| 948 |
} |
| 949 |
return files |
| 950 |
} |
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
func (s *Snapshot) WorkspaceMetadata(ctx context.Context) ([]*metadata.Package, error) { |
| 964 |
if err := s.awaitLoaded(ctx); err != nil { |
| 965 |
return nil, err |
| 966 |
} |
| 967 |
|
| 968 |
s.mu.Lock() |
| 969 |
defer s.mu.Unlock() |
| 970 |
|
| 971 |
meta := make([]*metadata.Package, 0, s.workspacePackages.Len()) |
| 972 |
for id := range s.workspacePackages.All() { |
| 973 |
meta = append(meta, s.meta.Packages[id]) |
| 974 |
} |
| 975 |
return meta, nil |
| 976 |
} |
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
func (s *Snapshot) WorkspacePackages() immutable.Map[PackageID, PackagePath] { |
| 983 |
s.mu.Lock() |
| 984 |
defer s.mu.Unlock() |
| 985 |
return s.workspacePackages |
| 986 |
} |
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
|
| 991 |
func (s *Snapshot) IsWorkspacePackage(id PackageID) bool { |
| 992 |
s.mu.Lock() |
| 993 |
defer s.mu.Unlock() |
| 994 |
_, ok := s.workspacePackages.Value(id) |
| 995 |
return ok |
| 996 |
} |
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
|
| 1007 |
func (s *Snapshot) AllMetadata(ctx context.Context) ([]*metadata.Package, error) { |
| 1008 |
g, err := s.LoadMetadataGraph(ctx) |
| 1009 |
if err != nil { |
| 1010 |
return nil, err |
| 1011 |
} |
| 1012 |
return moremaps.ValueSlice(g.Packages), nil |
| 1013 |
} |
| 1014 |
|
| 1015 |
|
| 1016 |
|
| 1017 |
|
| 1018 |
|
| 1019 |
func (s *Snapshot) GoModForFile(uri protocol.DocumentURI) protocol.DocumentURI { |
| 1020 |
return moduleForURI(s.view.workspaceModFiles, uri) |
| 1021 |
} |
| 1022 |
|
| 1023 |
func moduleForURI(modFiles map[protocol.DocumentURI]struct{}, uri protocol.DocumentURI) protocol.DocumentURI { |
| 1024 |
var match protocol.DocumentURI |
| 1025 |
for modURI := range modFiles { |
| 1026 |
if !modURI.Dir().Encloses(uri) { |
| 1027 |
continue |
| 1028 |
} |
| 1029 |
if len(modURI) > len(match) { |
| 1030 |
match = modURI |
| 1031 |
} |
| 1032 |
} |
| 1033 |
return match |
| 1034 |
} |
| 1035 |
|
| 1036 |
|
| 1037 |
|
| 1038 |
func (s *Snapshot) Metadata(id PackageID) *metadata.Package { |
| 1039 |
s.mu.Lock() |
| 1040 |
defer s.mu.Unlock() |
| 1041 |
return s.meta.Packages[id] |
| 1042 |
} |
| 1043 |
|
| 1044 |
|
| 1045 |
|
| 1046 |
func (s *Snapshot) clearShouldLoad(scopes ...loadScope) { |
| 1047 |
s.mu.Lock() |
| 1048 |
defer s.mu.Unlock() |
| 1049 |
|
| 1050 |
for _, scope := range scopes { |
| 1051 |
switch scope := scope.(type) { |
| 1052 |
case packageLoadScope: |
| 1053 |
scopePath := PackagePath(scope) |
| 1054 |
var toDelete []PackageID |
| 1055 |
for id, pkgPaths := range s.shouldLoad.All() { |
| 1056 |
if slices.Contains(pkgPaths, scopePath) { |
| 1057 |
toDelete = append(toDelete, id) |
| 1058 |
} |
| 1059 |
} |
| 1060 |
for _, id := range toDelete { |
| 1061 |
s.shouldLoad.Delete(id) |
| 1062 |
} |
| 1063 |
case fileLoadScope: |
| 1064 |
uri := protocol.DocumentURI(scope) |
| 1065 |
for _, pkg := range s.meta.ForFile[uri] { |
| 1066 |
s.shouldLoad.Delete(pkg.ID) |
| 1067 |
} |
| 1068 |
} |
| 1069 |
} |
| 1070 |
} |
| 1071 |
|
| 1072 |
|
| 1073 |
|
| 1074 |
|
| 1075 |
|
| 1076 |
|
| 1077 |
func (s *Snapshot) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error) { |
| 1078 |
s.mu.Lock() |
| 1079 |
defer s.mu.Unlock() |
| 1080 |
|
| 1081 |
return lockedSnapshot{s}.ReadFile(ctx, uri) |
| 1082 |
} |
| 1083 |
|
| 1084 |
|
| 1085 |
|
| 1086 |
|
| 1087 |
|
| 1088 |
type lockedSnapshot struct { |
| 1089 |
s *Snapshot |
| 1090 |
} |
| 1091 |
|
| 1092 |
func (s lockedSnapshot) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error) { |
| 1093 |
fh, ok := s.s.files.get(uri) |
| 1094 |
if !ok { |
| 1095 |
var err error |
| 1096 |
fh, err = s.s.view.fs.ReadFile(ctx, uri) |
| 1097 |
if err != nil { |
| 1098 |
return nil, err |
| 1099 |
} |
| 1100 |
s.s.files.set(uri, fh) |
| 1101 |
} |
| 1102 |
return fh, nil |
| 1103 |
} |
| 1104 |
|
| 1105 |
|
| 1106 |
|
| 1107 |
func (s *Snapshot) preloadFiles(ctx context.Context, uris []protocol.DocumentURI) { |
| 1108 |
files := make([]file.Handle, len(uris)) |
| 1109 |
var wg sync.WaitGroup |
| 1110 |
iolimit := make(chan struct{}, 20) |
| 1111 |
for i, uri := range uris { |
| 1112 |
wg.Add(1) |
| 1113 |
iolimit <- struct{}{} |
| 1114 |
go func(i int, uri protocol.DocumentURI) { |
| 1115 |
defer wg.Done() |
| 1116 |
fh, err := s.view.fs.ReadFile(ctx, uri) |
| 1117 |
<-iolimit |
| 1118 |
if err != nil && ctx.Err() == nil { |
| 1119 |
event.Error(ctx, fmt.Sprintf("reading %s", uri), err) |
| 1120 |
return |
| 1121 |
} |
| 1122 |
files[i] = fh |
| 1123 |
}(i, uri) |
| 1124 |
} |
| 1125 |
wg.Wait() |
| 1126 |
|
| 1127 |
s.mu.Lock() |
| 1128 |
defer s.mu.Unlock() |
| 1129 |
|
| 1130 |
for i, fh := range files { |
| 1131 |
if fh == nil { |
| 1132 |
continue |
| 1133 |
} |
| 1134 |
uri := uris[i] |
| 1135 |
if _, ok := s.files.get(uri); !ok { |
| 1136 |
s.files.set(uri, fh) |
| 1137 |
} |
| 1138 |
} |
| 1139 |
} |
| 1140 |
|
| 1141 |
|
| 1142 |
func (s *Snapshot) IsOpen(uri protocol.DocumentURI) bool { |
| 1143 |
s.mu.Lock() |
| 1144 |
defer s.mu.Unlock() |
| 1145 |
|
| 1146 |
fh, _ := s.files.get(uri) |
| 1147 |
_, open := fh.(*overlay) |
| 1148 |
return open |
| 1149 |
} |
| 1150 |
|
| 1151 |
|
| 1152 |
func (s *Snapshot) MetadataGraph() *metadata.Graph { |
| 1153 |
s.mu.Lock() |
| 1154 |
defer s.mu.Unlock() |
| 1155 |
return s.meta |
| 1156 |
} |
| 1157 |
|
| 1158 |
|
| 1159 |
func (s *Snapshot) LoadMetadataGraph(ctx context.Context) (*metadata.Graph, error) { |
| 1160 |
if err := s.awaitLoaded(ctx); err != nil { |
| 1161 |
return nil, err |
| 1162 |
} |
| 1163 |
return s.MetadataGraph(), nil |
| 1164 |
} |
| 1165 |
|
| 1166 |
|
| 1167 |
func (s *Snapshot) InitializationError() *InitializationError { |
| 1168 |
s.mu.Lock() |
| 1169 |
defer s.mu.Unlock() |
| 1170 |
return s.initialErr |
| 1171 |
} |
| 1172 |
|
| 1173 |
|
| 1174 |
|
| 1175 |
func (s *Snapshot) awaitLoaded(ctx context.Context) error { |
| 1176 |
|
| 1177 |
s.AwaitInitialized(ctx) |
| 1178 |
s.reloadWorkspace(ctx) |
| 1179 |
return ctx.Err() |
| 1180 |
} |
| 1181 |
|
| 1182 |
|
| 1183 |
func (s *Snapshot) AwaitInitialized(ctx context.Context) { |
| 1184 |
select { |
| 1185 |
case <-ctx.Done(): |
| 1186 |
return |
| 1187 |
case <-s.view.initialWorkspaceLoad: |
| 1188 |
} |
| 1189 |
|
| 1190 |
|
| 1191 |
s.initialize(ctx, false) |
| 1192 |
} |
| 1193 |
|
| 1194 |
|
| 1195 |
func (s *Snapshot) reloadWorkspace(ctx context.Context) { |
| 1196 |
if ctx.Err() != nil { |
| 1197 |
return |
| 1198 |
} |
| 1199 |
|
| 1200 |
var scopes []loadScope |
| 1201 |
var seen map[PackagePath]bool |
| 1202 |
s.mu.Lock() |
| 1203 |
for _, pkgPaths := range s.shouldLoad.All() { |
| 1204 |
for _, pkgPath := range pkgPaths { |
| 1205 |
if seen == nil { |
| 1206 |
seen = make(map[PackagePath]bool) |
| 1207 |
} |
| 1208 |
if seen[pkgPath] { |
| 1209 |
continue |
| 1210 |
} |
| 1211 |
seen[pkgPath] = true |
| 1212 |
scopes = append(scopes, packageLoadScope(pkgPath)) |
| 1213 |
} |
| 1214 |
} |
| 1215 |
s.mu.Unlock() |
| 1216 |
|
| 1217 |
if len(scopes) == 0 { |
| 1218 |
return |
| 1219 |
} |
| 1220 |
|
| 1221 |
|
| 1222 |
if s.view.typ == AdHocView { |
| 1223 |
scopes = []loadScope{viewLoadScope{}} |
| 1224 |
} |
| 1225 |
|
| 1226 |
err := s.load(ctx, NoNetwork, scopes...) |
| 1227 |
|
| 1228 |
|
| 1229 |
|
| 1230 |
if !errors.Is(err, context.Canceled) { |
| 1231 |
s.clearShouldLoad(scopes...) |
| 1232 |
if err != nil { |
| 1233 |
event.Error(ctx, "reloading workspace", err, s.Labels()...) |
| 1234 |
} |
| 1235 |
} |
| 1236 |
} |
| 1237 |
|
| 1238 |
func (s *Snapshot) orphanedFileDiagnostics(ctx context.Context, overlays []*overlay) ([]*Diagnostic, error) { |
| 1239 |
if err := s.awaitLoaded(ctx); err != nil { |
| 1240 |
return nil, err |
| 1241 |
} |
| 1242 |
|
| 1243 |
var diagnostics []*Diagnostic |
| 1244 |
var orphaned []*overlay |
| 1245 |
searchOverlays: |
| 1246 |
for _, o := range overlays { |
| 1247 |
uri := o.URI() |
| 1248 |
if s.IsBuiltin(uri) || s.FileKind(o) != file.Go { |
| 1249 |
continue |
| 1250 |
} |
| 1251 |
mps, err := s.MetadataForFile(ctx, uri, true) |
| 1252 |
if err != nil { |
| 1253 |
return nil, err |
| 1254 |
} |
| 1255 |
for _, mp := range mps { |
| 1256 |
if !metadata.IsCommandLineArguments(mp.ID) || mp.Standalone { |
| 1257 |
continue searchOverlays |
| 1258 |
} |
| 1259 |
} |
| 1260 |
|
| 1261 |
|
| 1262 |
|
| 1263 |
|
| 1264 |
|
| 1265 |
|
| 1266 |
|
| 1267 |
|
| 1268 |
|
| 1269 |
if len(mps) > 0 { |
| 1270 |
diags, err := s.PackageDiagnostics(ctx, mps[0].ID) |
| 1271 |
if err != nil { |
| 1272 |
return nil, err |
| 1273 |
} |
| 1274 |
diagnostics = append(diagnostics, diags[uri]...) |
| 1275 |
} |
| 1276 |
orphaned = append(orphaned, o) |
| 1277 |
} |
| 1278 |
|
| 1279 |
if len(orphaned) == 0 { |
| 1280 |
return nil, nil |
| 1281 |
} |
| 1282 |
|
| 1283 |
loadedModFiles := make(map[protocol.DocumentURI]struct{}) |
| 1284 |
ignoredFiles := make(map[protocol.DocumentURI]bool) |
| 1285 |
|
| 1286 |
g := s.MetadataGraph() |
| 1287 |
for _, meta := range g.Packages { |
| 1288 |
if meta.Module != nil && meta.Module.GoMod != "" { |
| 1289 |
gomod := protocol.URIFromPath(meta.Module.GoMod) |
| 1290 |
loadedModFiles[gomod] = struct{}{} |
| 1291 |
} |
| 1292 |
for _, ignored := range meta.IgnoredFiles { |
| 1293 |
ignoredFiles[ignored] = true |
| 1294 |
} |
| 1295 |
} |
| 1296 |
|
| 1297 |
initialErr := s.InitializationError() |
| 1298 |
|
| 1299 |
for _, fh := range orphaned { |
| 1300 |
pgf, rng, ok := orphanedFileDiagnosticRange(ctx, s.view.parseCache, fh) |
| 1301 |
if !ok { |
| 1302 |
continue |
| 1303 |
} |
| 1304 |
|
| 1305 |
var ( |
| 1306 |
msg string |
| 1307 |
suggestedFixes []SuggestedFix |
| 1308 |
) |
| 1309 |
if initialErr != nil { |
| 1310 |
msg = fmt.Sprintf("initialization failed: %v", initialErr.MainError) |
| 1311 |
} else if goMod, err := findRootPattern(ctx, fh.URI().Dir(), "go.mod", file.Source(s)); err == nil && goMod != "" { |
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 1315 |
|
| 1316 |
|
| 1317 |
_, loadedMod := loadedModFiles[goMod] |
| 1318 |
_, workspaceMod := s.view.workspaceModFiles[goMod] |
| 1319 |
|
| 1320 |
|
| 1321 |
|
| 1322 |
|
| 1323 |
if !(loadedMod || workspaceMod) { |
| 1324 |
modDir := goMod.DirPath() |
| 1325 |
viewDir := s.view.folder.Dir.Path() |
| 1326 |
|
| 1327 |
|
| 1328 |
|
| 1329 |
inDir := pathutil.InDir(viewDir, modDir) |
| 1330 |
|
| 1331 |
if rel, err := filepath.Rel(viewDir, modDir); err == nil { |
| 1332 |
modDir = rel |
| 1333 |
} |
| 1334 |
|
| 1335 |
var fix string |
| 1336 |
if s.view.folder.Env.GoVersion >= 18 { |
| 1337 |
if s.view.gowork != "" { |
| 1338 |
fix = fmt.Sprintf("To fix this problem, you can add this module to your go.work file (%s)", s.view.gowork) |
| 1339 |
|
| 1340 |
cmd := command.NewRunGoWorkCommandCommand("Run `go work use`", command.RunGoWorkArgs{ |
| 1341 |
ViewID: s.view.ID(), |
| 1342 |
Args: []string{"use", modDir}, |
| 1343 |
}) |
| 1344 |
suggestedFixes = append(suggestedFixes, SuggestedFix{ |
| 1345 |
Title: "Use this module in your go.work file", |
| 1346 |
Command: cmd, |
| 1347 |
ActionKind: protocol.QuickFix, |
| 1348 |
}) |
| 1349 |
|
| 1350 |
if inDir { |
| 1351 |
cmd := command.NewRunGoWorkCommandCommand("Run `go work use -r`", command.RunGoWorkArgs{ |
| 1352 |
ViewID: s.view.ID(), |
| 1353 |
Args: []string{"use", "-r", "."}, |
| 1354 |
}) |
| 1355 |
suggestedFixes = append(suggestedFixes, SuggestedFix{ |
| 1356 |
Title: "Use all modules in your workspace", |
| 1357 |
Command: cmd, |
| 1358 |
ActionKind: protocol.QuickFix, |
| 1359 |
}) |
| 1360 |
} |
| 1361 |
} else { |
| 1362 |
fix = "To fix this problem, you can add a go.work file that uses this directory." |
| 1363 |
|
| 1364 |
cmd := command.NewRunGoWorkCommandCommand("Run `go work init && go work use`", command.RunGoWorkArgs{ |
| 1365 |
ViewID: s.view.ID(), |
| 1366 |
InitFirst: true, |
| 1367 |
Args: []string{"use", modDir}, |
| 1368 |
}) |
| 1369 |
suggestedFixes = []SuggestedFix{ |
| 1370 |
{ |
| 1371 |
Title: "Add a go.work file using this module", |
| 1372 |
Command: cmd, |
| 1373 |
ActionKind: protocol.QuickFix, |
| 1374 |
}, |
| 1375 |
} |
| 1376 |
|
| 1377 |
if inDir { |
| 1378 |
cmd := command.NewRunGoWorkCommandCommand("Run `go work init && go work use -r`", command.RunGoWorkArgs{ |
| 1379 |
ViewID: s.view.ID(), |
| 1380 |
InitFirst: true, |
| 1381 |
Args: []string{"use", "-r", "."}, |
| 1382 |
}) |
| 1383 |
suggestedFixes = append(suggestedFixes, SuggestedFix{ |
| 1384 |
Title: "Add a go.work file using all modules in your workspace", |
| 1385 |
Command: cmd, |
| 1386 |
ActionKind: protocol.QuickFix, |
| 1387 |
}) |
| 1388 |
} |
| 1389 |
} |
| 1390 |
} else { |
| 1391 |
fix = `To work with multiple modules simultaneously, please upgrade to Go 1.18 or |
| 1392 |
later, reinstall gopls, and use a go.work file.` |
| 1393 |
} |
| 1394 |
|
| 1395 |
msg = fmt.Sprintf(`This file is within module %q, which is not included in your workspace. |
| 1396 |
%s |
| 1397 |
See the documentation for more information on setting up your workspace: |
| 1398 |
https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.`, modDir, fix) |
| 1399 |
} |
| 1400 |
} |
| 1401 |
|
| 1402 |
if msg == "" { |
| 1403 |
if ignoredFiles[fh.URI()] { |
| 1404 |
|
| 1405 |
|
| 1406 |
hasConstraint := false |
| 1407 |
walkConstraints(pgf.File, func(constraint.Expr) bool { |
| 1408 |
hasConstraint = true |
| 1409 |
return false |
| 1410 |
}) |
| 1411 |
var fix string |
| 1412 |
if hasConstraint { |
| 1413 |
fix = `This file may be excluded due to its build tags; try adding "-tags=<build tag>" to your gopls "buildFlags" configuration |
| 1414 |
See the documentation for more information on working with build tags: |
| 1415 |
https://github.com/golang/tools/blob/master/gopls/doc/settings.md#buildflags.` |
| 1416 |
} else if strings.Contains(fh.URI().Base(), "_") { |
| 1417 |
fix = `This file may be excluded due to its GOOS/GOARCH, or other build constraints.` |
| 1418 |
} else { |
| 1419 |
fix = `This file is ignored by your gopls build.` |
| 1420 |
} |
| 1421 |
msg = fmt.Sprintf("No packages found for open file %s.\n%s", fh.URI().Path(), fix) |
| 1422 |
} else { |
| 1423 |
|
| 1424 |
|
| 1425 |
|
| 1426 |
msg = fmt.Sprintf("No packages found for open file %s.", fh.URI().Path()) |
| 1427 |
} |
| 1428 |
} |
| 1429 |
|
| 1430 |
if msg != "" { |
| 1431 |
d := &Diagnostic{ |
| 1432 |
URI: fh.URI(), |
| 1433 |
Range: rng, |
| 1434 |
Severity: protocol.SeverityWarning, |
| 1435 |
Source: ListError, |
| 1436 |
Message: msg, |
| 1437 |
SuggestedFixes: suggestedFixes, |
| 1438 |
} |
| 1439 |
if ok := bundleLazyFixes(d); !ok { |
| 1440 |
bug.Reportf("failed to bundle quick fixes for %v", d) |
| 1441 |
} |
| 1442 |
|
| 1443 |
diagnostics = append(diagnostics, d) |
| 1444 |
} |
| 1445 |
} |
| 1446 |
return diagnostics, nil |
| 1447 |
} |
| 1448 |
|
| 1449 |
|
| 1450 |
|
| 1451 |
|
| 1452 |
func orphanedFileDiagnosticRange(ctx context.Context, cache *parseCache, fh file.Handle) (*parsego.File, protocol.Range, bool) { |
| 1453 |
pgfs, err := cache.parseFiles(ctx, token.NewFileSet(), parsego.Header, false, fh) |
| 1454 |
if err != nil { |
| 1455 |
return nil, protocol.Range{}, false |
| 1456 |
} |
| 1457 |
pgf := pgfs[0] |
| 1458 |
name := pgf.File.Name |
| 1459 |
if !name.Pos().IsValid() { |
| 1460 |
return nil, protocol.Range{}, false |
| 1461 |
} |
| 1462 |
rng, err := pgf.PosRange(name.Pos(), name.End()) |
| 1463 |
if err != nil { |
| 1464 |
return nil, protocol.Range{}, false |
| 1465 |
} |
| 1466 |
return pgf, rng, true |
| 1467 |
} |
| 1468 |
|
| 1469 |
|
| 1470 |
|
| 1471 |
|
| 1472 |
|
| 1473 |
|
| 1474 |
|
| 1475 |
|
| 1476 |
func inVendor(uri protocol.DocumentURI) bool { |
| 1477 |
_, after, found := strings.Cut(string(uri), "/vendor/") |
| 1478 |
|
| 1479 |
|
| 1480 |
return found && strings.Contains(after, "/") |
| 1481 |
} |
| 1482 |
|
| 1483 |
|
| 1484 |
|
| 1485 |
|
| 1486 |
|
| 1487 |
|
| 1488 |
|
| 1489 |
|
| 1490 |
|
| 1491 |
|
| 1492 |
|
| 1493 |
|
| 1494 |
|
| 1495 |
|
| 1496 |
|
| 1497 |
|
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
|
| 1503 |
func (s *Snapshot) clone(ctx, bgCtx context.Context, changed StateChange, done func()) (*Snapshot, bool) { |
| 1504 |
changedFiles := changed.Files |
| 1505 |
ctx, stop := event.Start(ctx, "cache.snapshot.clone") |
| 1506 |
defer stop() |
| 1507 |
|
| 1508 |
s.mu.Lock() |
| 1509 |
defer s.mu.Unlock() |
| 1510 |
|
| 1511 |
|
| 1512 |
|
| 1513 |
needsDiagnosis := len(changed.CompilerOptDetails) > 0 || len(changed.ModuleUpgrades) > 0 || len(changed.Vulns) > 0 |
| 1514 |
|
| 1515 |
bgCtx, cancel := context.WithCancel(bgCtx) |
| 1516 |
result := &Snapshot{ |
| 1517 |
sequenceID: s.sequenceID + 1, |
| 1518 |
store: s.store, |
| 1519 |
refcount: 1, |
| 1520 |
done: done, |
| 1521 |
view: s.view, |
| 1522 |
backgroundCtx: bgCtx, |
| 1523 |
cancel: cancel, |
| 1524 |
builtin: s.builtin, |
| 1525 |
initialized: s.initialized, |
| 1526 |
initialErr: s.initialErr, |
| 1527 |
packages: s.packages.Clone(), |
| 1528 |
fullAnalysisKeys: s.fullAnalysisKeys.Clone(), |
| 1529 |
factyAnalysisKeys: s.factyAnalysisKeys.Clone(), |
| 1530 |
files: s.files.clone(changedFiles), |
| 1531 |
workspacePackages: s.workspacePackages, |
| 1532 |
shouldLoad: s.shouldLoad.Clone(), |
| 1533 |
unloadableFiles: s.unloadableFiles.Clone(), |
| 1534 |
parseModHandles: cloneWithout(s.parseModHandles, changedFiles, &needsDiagnosis), |
| 1535 |
parseWorkHandles: cloneWithout(s.parseWorkHandles, changedFiles, &needsDiagnosis), |
| 1536 |
modTidyHandles: cloneWithout(s.modTidyHandles, changedFiles, &needsDiagnosis), |
| 1537 |
modWhyHandles: cloneWithout(s.modWhyHandles, changedFiles, &needsDiagnosis), |
| 1538 |
modVulnHandles: cloneWithout(s.modVulnHandles, changedFiles, &needsDiagnosis), |
| 1539 |
moduleUpgrades: cloneWith(s.moduleUpgrades, changed.ModuleUpgrades), |
| 1540 |
vulns: cloneWith(s.vulns, changed.Vulns), |
| 1541 |
} |
| 1542 |
|
| 1543 |
|
| 1544 |
|
| 1545 |
if len(s.compilerOptDetails) > 0 || len(changed.CompilerOptDetails) > 0 { |
| 1546 |
newCompilerOptDetails := make(map[protocol.DocumentURI]unit) |
| 1547 |
for dir := range s.compilerOptDetails { |
| 1548 |
if _, ok := changed.CompilerOptDetails[dir]; !ok { |
| 1549 |
newCompilerOptDetails[dir] = unit{} |
| 1550 |
} |
| 1551 |
} |
| 1552 |
for dir, want := range changed.CompilerOptDetails { |
| 1553 |
if want { |
| 1554 |
newCompilerOptDetails[dir] = unit{} |
| 1555 |
} |
| 1556 |
} |
| 1557 |
if len(newCompilerOptDetails) > 0 { |
| 1558 |
result.compilerOptDetails = newCompilerOptDetails |
| 1559 |
} |
| 1560 |
} |
| 1561 |
|
| 1562 |
reinit := false |
| 1563 |
for _, mod := range changed.Modifications { |
| 1564 |
|
| 1565 |
|
| 1566 |
|
| 1567 |
|
| 1568 |
|
| 1569 |
|
| 1570 |
|
| 1571 |
|
| 1572 |
|
| 1573 |
|
| 1574 |
if inVendor(mod.URI) && (mod.Action == file.Create || mod.Action == file.Delete) || |
| 1575 |
strings.HasSuffix(string(mod.URI), "/vendor/modules.txt") { |
| 1576 |
|
| 1577 |
reinit = true |
| 1578 |
break |
| 1579 |
} |
| 1580 |
|
| 1581 |
|
| 1582 |
|
| 1583 |
|
| 1584 |
if isWorkspaceFile(mod.URI, s.view.folder.Options.WorkspaceFiles) && (mod.Action == file.Save || mod.OnDisk) { |
| 1585 |
reinit = true |
| 1586 |
break |
| 1587 |
} |
| 1588 |
} |
| 1589 |
|
| 1590 |
|
| 1591 |
|
| 1592 |
|
| 1593 |
|
| 1594 |
|
| 1595 |
|
| 1596 |
|
| 1597 |
|
| 1598 |
|
| 1599 |
oldFiles := make(map[protocol.DocumentURI]file.Handle) |
| 1600 |
for uri := range changedFiles { |
| 1601 |
if fh, ok := s.files.get(uri); ok { |
| 1602 |
oldFiles[uri] = fh |
| 1603 |
} |
| 1604 |
} |
| 1605 |
|
| 1606 |
|
| 1607 |
|
| 1608 |
|
| 1609 |
|
| 1610 |
changedOnDisk := func(oldFH, newFH file.Handle) bool { |
| 1611 |
if !newFH.SameContentsOnDisk() { |
| 1612 |
return false |
| 1613 |
} |
| 1614 |
if oe, ne := (oldFH != nil && fileExists(oldFH)), fileExists(newFH); !oe || !ne { |
| 1615 |
return oe != ne |
| 1616 |
} |
| 1617 |
return !oldFH.SameContentsOnDisk() || oldFH.Identity() != newFH.Identity() |
| 1618 |
} |
| 1619 |
|
| 1620 |
|
| 1621 |
for uri, newFH := range changedFiles { |
| 1622 |
if _, ok := result.view.workspaceModFiles[uri]; ok && changedOnDisk(oldFiles[uri], newFH) { |
| 1623 |
reinit = true |
| 1624 |
} |
| 1625 |
} |
| 1626 |
|
| 1627 |
|
| 1628 |
for uri, newFH := range changedFiles { |
| 1629 |
if !changedOnDisk(oldFiles[uri], newFH) { |
| 1630 |
continue |
| 1631 |
} |
| 1632 |
dir, base := filepath.Split(uri.Path()) |
| 1633 |
if base == "go.work.sum" && s.view.typ == GoWorkView && dir == s.view.gowork.DirPath() { |
| 1634 |
reinit = true |
| 1635 |
} |
| 1636 |
if base == "go.sum" { |
| 1637 |
modURI := protocol.URIFromPath(filepath.Join(dir, "go.mod")) |
| 1638 |
if _, active := result.view.workspaceModFiles[modURI]; active { |
| 1639 |
reinit = true |
| 1640 |
} |
| 1641 |
} |
| 1642 |
} |
| 1643 |
|
| 1644 |
|
| 1645 |
|
| 1646 |
if reinit { |
| 1647 |
result.initialized = false |
| 1648 |
needsDiagnosis = true |
| 1649 |
} |
| 1650 |
|
| 1651 |
|
| 1652 |
|
| 1653 |
directIDs := map[PackageID]bool{} |
| 1654 |
|
| 1655 |
|
| 1656 |
if reinit { |
| 1657 |
for k := range s.meta.Packages { |
| 1658 |
|
| 1659 |
directIDs[k] = true |
| 1660 |
} |
| 1661 |
} |
| 1662 |
|
| 1663 |
|
| 1664 |
anyImportDeleted := false |
| 1665 |
anyFileOpenedOrClosed := false |
| 1666 |
anyPkgFileChanged := false |
| 1667 |
|
| 1668 |
for uri, newFH := range changedFiles { |
| 1669 |
|
| 1670 |
oldFH := oldFiles[uri] |
| 1671 |
_, oldOpen := oldFH.(*overlay) |
| 1672 |
_, newOpen := newFH.(*overlay) |
| 1673 |
|
| 1674 |
|
| 1675 |
|
| 1676 |
anyFileOpenedOrClosed = anyFileOpenedOrClosed || (oldOpen != newOpen) |
| 1677 |
anyPkgFileChanged = anyPkgFileChanged || (oldFH == nil || !fileExists(oldFH)) && fileExists(newFH) |
| 1678 |
|
| 1679 |
|
| 1680 |
|
| 1681 |
|
| 1682 |
|
| 1683 |
var invalidateMetadata, pkgFileChanged, importDeleted bool |
| 1684 |
if strings.HasSuffix(uri.Path(), ".go") { |
| 1685 |
invalidateMetadata, pkgFileChanged, importDeleted = metadataChanges(ctx, s, oldFH, newFH) |
| 1686 |
} |
| 1687 |
if invalidateMetadata { |
| 1688 |
|
| 1689 |
result.unloadableFiles.Remove(uri) |
| 1690 |
needsDiagnosis = true |
| 1691 |
} |
| 1692 |
|
| 1693 |
invalidateMetadata = invalidateMetadata || reinit |
| 1694 |
anyImportDeleted = anyImportDeleted || importDeleted |
| 1695 |
anyPkgFileChanged = anyPkgFileChanged || pkgFileChanged |
| 1696 |
|
| 1697 |
|
| 1698 |
filePackageIDs := invalidatedPackageIDs(uri, s.meta.ForFile, pkgFileChanged) |
| 1699 |
for id := range filePackageIDs { |
| 1700 |
directIDs[id] = directIDs[id] || invalidateMetadata |
| 1701 |
} |
| 1702 |
|
| 1703 |
|
| 1704 |
|
| 1705 |
|
| 1706 |
|
| 1707 |
|
| 1708 |
|
| 1709 |
|
| 1710 |
if invalidateMetadata || fileWasSaved(oldFH, newFH) { |
| 1711 |
|
| 1712 |
|
| 1713 |
|
| 1714 |
|
| 1715 |
|
| 1716 |
|
| 1717 |
|
| 1718 |
|
| 1719 |
|
| 1720 |
|
| 1721 |
|
| 1722 |
|
| 1723 |
|
| 1724 |
|
| 1725 |
|
| 1726 |
|
| 1727 |
|
| 1728 |
|
| 1729 |
|
| 1730 |
const onlyInvalidateMostRelevant = true |
| 1731 |
if onlyInvalidateMostRelevant { |
| 1732 |
deleteMostRelevantModFile(result.modTidyHandles, uri) |
| 1733 |
} else { |
| 1734 |
result.modTidyHandles.Clear() |
| 1735 |
} |
| 1736 |
|
| 1737 |
|
| 1738 |
|
| 1739 |
|
| 1740 |
|
| 1741 |
result.modWhyHandles.Clear() |
| 1742 |
result.modVulnHandles.Clear() |
| 1743 |
} |
| 1744 |
} |
| 1745 |
|
| 1746 |
|
| 1747 |
|
| 1748 |
|
| 1749 |
|
| 1750 |
|
| 1751 |
|
| 1752 |
|
| 1753 |
|
| 1754 |
|
| 1755 |
|
| 1756 |
|
| 1757 |
|
| 1758 |
|
| 1759 |
if anyImportDeleted { |
| 1760 |
for id, mp := range s.meta.Packages { |
| 1761 |
if len(mp.Errors) > 0 { |
| 1762 |
directIDs[id] = true |
| 1763 |
} |
| 1764 |
} |
| 1765 |
} |
| 1766 |
|
| 1767 |
|
| 1768 |
|
| 1769 |
|
| 1770 |
|
| 1771 |
|
| 1772 |
if anyPkgFileChanged { |
| 1773 |
for id, mp := range s.meta.Packages { |
| 1774 |
for _, impID := range mp.DepsByImpPath { |
| 1775 |
if impID == "" { |
| 1776 |
directIDs[id] = true |
| 1777 |
break |
| 1778 |
} |
| 1779 |
} |
| 1780 |
} |
| 1781 |
} |
| 1782 |
|
| 1783 |
|
| 1784 |
|
| 1785 |
|
| 1786 |
|
| 1787 |
idsToInvalidate := map[PackageID]bool{} |
| 1788 |
var addRevDeps func(PackageID, bool) |
| 1789 |
addRevDeps = func(id PackageID, invalidateMetadata bool) { |
| 1790 |
current, seen := idsToInvalidate[id] |
| 1791 |
newInvalidateMetadata := current || invalidateMetadata |
| 1792 |
|
| 1793 |
|
| 1794 |
|
| 1795 |
if seen && current == newInvalidateMetadata { |
| 1796 |
return |
| 1797 |
} |
| 1798 |
idsToInvalidate[id] = newInvalidateMetadata |
| 1799 |
for _, rdep := range s.meta.ImportedBy[id] { |
| 1800 |
addRevDeps(rdep.ID, invalidateMetadata) |
| 1801 |
} |
| 1802 |
} |
| 1803 |
for id, invalidateMetadata := range directIDs { |
| 1804 |
addRevDeps(id, invalidateMetadata) |
| 1805 |
} |
| 1806 |
|
| 1807 |
|
| 1808 |
for id, invalidateMetadata := range idsToInvalidate { |
| 1809 |
|
| 1810 |
|
| 1811 |
if ph, ok := result.packages.Get(id); ok { |
| 1812 |
needsDiagnosis = true |
| 1813 |
|
| 1814 |
|
| 1815 |
|
| 1816 |
result.fullAnalysisKeys.Delete(id) |
| 1817 |
result.factyAnalysisKeys.Delete(id) |
| 1818 |
|
| 1819 |
if invalidateMetadata { |
| 1820 |
result.packages.Delete(id) |
| 1821 |
} else { |
| 1822 |
|
| 1823 |
|
| 1824 |
ph = ph.clone() |
| 1825 |
if _, ok := directIDs[id]; ok { |
| 1826 |
ph.state = validMetadata |
| 1827 |
} else { |
| 1828 |
ph.state = min(ph.state, validLocalData) |
| 1829 |
} |
| 1830 |
result.packages.Set(id, ph, nil) |
| 1831 |
} |
| 1832 |
} |
| 1833 |
} |
| 1834 |
|
| 1835 |
|
| 1836 |
|
| 1837 |
|
| 1838 |
metadataUpdates := make(map[PackageID]*metadata.Package) |
| 1839 |
for id, mp := range s.meta.Packages { |
| 1840 |
invalidateMetadata := idsToInvalidate[id] |
| 1841 |
|
| 1842 |
|
| 1843 |
|
| 1844 |
if invalidateMetadata && !metadata.IsCommandLineArguments(mp.ID) { |
| 1845 |
needsReload := []PackagePath{mp.PkgPath} |
| 1846 |
if mp.ForTest != "" && mp.ForTest != mp.PkgPath { |
| 1847 |
|
| 1848 |
|
| 1849 |
|
| 1850 |
|
| 1851 |
|
| 1852 |
|
| 1853 |
needsReload = append(needsReload, mp.ForTest) |
| 1854 |
} |
| 1855 |
result.shouldLoad.Set(id, needsReload, nil) |
| 1856 |
} |
| 1857 |
|
| 1858 |
|
| 1859 |
if invalidateMetadata { |
| 1860 |
needsDiagnosis = true |
| 1861 |
metadataUpdates[id] = nil |
| 1862 |
continue |
| 1863 |
} |
| 1864 |
} |
| 1865 |
|
| 1866 |
|
| 1867 |
result.meta = s.meta.Update(metadataUpdates) |
| 1868 |
|
| 1869 |
|
| 1870 |
if result.meta != s.meta || anyFileOpenedOrClosed { |
| 1871 |
needsDiagnosis = true |
| 1872 |
result.workspacePackages = computeWorkspacePackagesLocked(ctx, result, result.meta) |
| 1873 |
} else { |
| 1874 |
result.workspacePackages = s.workspacePackages |
| 1875 |
} |
| 1876 |
|
| 1877 |
return result, needsDiagnosis |
| 1878 |
} |
| 1879 |
|
| 1880 |
|
| 1881 |
|
| 1882 |
|
| 1883 |
func cloneWithout[K constraints.Ordered, V1, V2 any](m *persistent.Map[K, V1], changes map[K]V2, didDelete *bool) *persistent.Map[K, V1] { |
| 1884 |
m2 := m.Clone() |
| 1885 |
for k := range changes { |
| 1886 |
if m2.Delete(k) && didDelete != nil { |
| 1887 |
*didDelete = true |
| 1888 |
} |
| 1889 |
} |
| 1890 |
return m2 |
| 1891 |
} |
| 1892 |
|
| 1893 |
|
| 1894 |
func cloneWith[K constraints.Ordered, V any](m *persistent.Map[K, V], changes map[K]V) *persistent.Map[K, V] { |
| 1895 |
m2 := m.Clone() |
| 1896 |
for k, v := range changes { |
| 1897 |
m2.Set(k, v, nil) |
| 1898 |
} |
| 1899 |
return m2 |
| 1900 |
} |
| 1901 |
|
| 1902 |
|
| 1903 |
|
| 1904 |
|
| 1905 |
|
| 1906 |
|
| 1907 |
|
| 1908 |
|
| 1909 |
|
| 1910 |
func deleteMostRelevantModFile(m *persistent.Map[protocol.DocumentURI, *memoize.Promise], changed protocol.DocumentURI) { |
| 1911 |
var mostRelevant protocol.DocumentURI |
| 1912 |
changedFile := changed.Path() |
| 1913 |
|
| 1914 |
for modURI := range m.All() { |
| 1915 |
if len(modURI) > len(mostRelevant) { |
| 1916 |
if pathutil.InDir(modURI.DirPath(), changedFile) { |
| 1917 |
mostRelevant = modURI |
| 1918 |
} |
| 1919 |
} |
| 1920 |
} |
| 1921 |
if mostRelevant != "" { |
| 1922 |
m.Delete(mostRelevant) |
| 1923 |
} |
| 1924 |
} |
| 1925 |
|
| 1926 |
|
| 1927 |
|
| 1928 |
|
| 1929 |
|
| 1930 |
|
| 1931 |
|
| 1932 |
|
| 1933 |
|
| 1934 |
func invalidatedPackageIDs(uri protocol.DocumentURI, known map[protocol.DocumentURI][]*metadata.Package, packageFileChanged bool) map[PackageID]struct{} { |
| 1935 |
invalidated := make(map[PackageID]struct{}) |
| 1936 |
|
| 1937 |
|
| 1938 |
for _, pkg := range known[uri] { |
| 1939 |
invalidated[pkg.ID] = struct{}{} |
| 1940 |
} |
| 1941 |
|
| 1942 |
|
| 1943 |
|
| 1944 |
if !packageFileChanged && len(invalidated) > 0 { |
| 1945 |
return invalidated |
| 1946 |
} |
| 1947 |
|
| 1948 |
|
| 1949 |
|
| 1950 |
|
| 1951 |
|
| 1952 |
|
| 1953 |
stats := make(map[string]struct { |
| 1954 |
os.FileInfo |
| 1955 |
error |
| 1956 |
}) |
| 1957 |
getInfo := func(dir string) (os.FileInfo, error) { |
| 1958 |
if res, ok := stats[dir]; ok { |
| 1959 |
return res.FileInfo, res.error |
| 1960 |
} |
| 1961 |
fi, err := os.Stat(dir) |
| 1962 |
stats[dir] = struct { |
| 1963 |
os.FileInfo |
| 1964 |
error |
| 1965 |
}{fi, err} |
| 1966 |
return fi, err |
| 1967 |
} |
| 1968 |
dir := uri.DirPath() |
| 1969 |
fi, err := getInfo(dir) |
| 1970 |
if err == nil { |
| 1971 |
|
| 1972 |
for knownURI, pkgs := range known { |
| 1973 |
knownDir := knownURI.DirPath() |
| 1974 |
knownFI, err := getInfo(knownDir) |
| 1975 |
if err != nil { |
| 1976 |
continue |
| 1977 |
} |
| 1978 |
if os.SameFile(fi, knownFI) { |
| 1979 |
for _, pkg := range pkgs { |
| 1980 |
invalidated[pkg.ID] = struct{}{} |
| 1981 |
} |
| 1982 |
} |
| 1983 |
} |
| 1984 |
} |
| 1985 |
return invalidated |
| 1986 |
} |
| 1987 |
|
| 1988 |
|
| 1989 |
|
| 1990 |
|
| 1991 |
|
| 1992 |
func fileWasSaved(originalFH, currentFH file.Handle) bool { |
| 1993 |
if originalFH == nil || currentFH == nil { |
| 1994 |
return true |
| 1995 |
} |
| 1996 |
|
| 1997 |
|
| 1998 |
|
| 1999 |
|
| 2000 |
if originalFH.Identity() == currentFH.Identity() { |
| 2001 |
return false |
| 2002 |
} |
| 2003 |
c, ok := currentFH.(*overlay) |
| 2004 |
if !ok || c == nil { |
| 2005 |
return true |
| 2006 |
} |
| 2007 |
o, ok := originalFH.(*overlay) |
| 2008 |
if !ok || o == nil { |
| 2009 |
return c.saved |
| 2010 |
} |
| 2011 |
return !o.saved && c.saved |
| 2012 |
} |
| 2013 |
|
| 2014 |
|
| 2015 |
|
| 2016 |
|
| 2017 |
|
| 2018 |
|
| 2019 |
|
| 2020 |
|
| 2021 |
|
| 2022 |
|
| 2023 |
|
| 2024 |
|
| 2025 |
|
| 2026 |
|
| 2027 |
|
| 2028 |
func metadataChanges(ctx context.Context, lockedSnapshot *Snapshot, oldFH, newFH file.Handle) (invalidate, pkgFileChanged, importDeleted bool) { |
| 2029 |
if oe, ne := oldFH != nil && fileExists(oldFH), fileExists(newFH); !oe || !ne { |
| 2030 |
changed := oe != ne |
| 2031 |
return changed, changed, !ne |
| 2032 |
} |
| 2033 |
|
| 2034 |
|
| 2035 |
if oldFH.Identity() == newFH.Identity() { |
| 2036 |
return false, false, false |
| 2037 |
} |
| 2038 |
|
| 2039 |
fset := token.NewFileSet() |
| 2040 |
|
| 2041 |
oldHeads, oldErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Header, false, oldFH) |
| 2042 |
newHeads, newErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Header, false, newFH) |
| 2043 |
|
| 2044 |
if oldErr != nil || newErr != nil { |
| 2045 |
errChanged := (oldErr == nil) != (newErr == nil) |
| 2046 |
return errChanged, errChanged, (newErr != nil) |
| 2047 |
} |
| 2048 |
|
| 2049 |
oldHead := oldHeads[0] |
| 2050 |
newHead := newHeads[0] |
| 2051 |
|
| 2052 |
|
| 2053 |
|
| 2054 |
if oldHead.ParseErr != nil && newHead.ParseErr == nil { |
| 2055 |
return true, true, true |
| 2056 |
} |
| 2057 |
|
| 2058 |
|
| 2059 |
|
| 2060 |
if oldHead.File.Name.Name != newHead.File.Name.Name { |
| 2061 |
return true, true, true |
| 2062 |
} |
| 2063 |
|
| 2064 |
|
| 2065 |
|
| 2066 |
oldImports := validImportPaths(oldHead.File.Imports) |
| 2067 |
newImports := validImportPaths(newHead.File.Imports) |
| 2068 |
|
| 2069 |
for path := range newImports { |
| 2070 |
if _, ok := oldImports[path]; ok { |
| 2071 |
delete(oldImports, path) |
| 2072 |
} else { |
| 2073 |
invalidate = true |
| 2074 |
} |
| 2075 |
} |
| 2076 |
|
| 2077 |
if len(oldImports) > 0 { |
| 2078 |
invalidate = true |
| 2079 |
importDeleted = true |
| 2080 |
} |
| 2081 |
|
| 2082 |
|
| 2083 |
|
| 2084 |
|
| 2085 |
|
| 2086 |
|
| 2087 |
if !invalidate { |
| 2088 |
origFulls, oldErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Full, false, oldFH) |
| 2089 |
newFulls, newErr := lockedSnapshot.view.parseCache.parseFiles(ctx, fset, parsego.Full, false, newFH) |
| 2090 |
if oldErr == nil && newErr == nil { |
| 2091 |
invalidate = magicCommentsChanged(origFulls[0].File, newFulls[0].File) |
| 2092 |
} else { |
| 2093 |
|
| 2094 |
|
| 2095 |
bug.Reportf("metadataChanges: unparsable file %v (old error: %v, new error: %v)", oldFH.URI(), oldErr, newErr) |
| 2096 |
} |
| 2097 |
} |
| 2098 |
|
| 2099 |
return invalidate, pkgFileChanged, importDeleted |
| 2100 |
} |
| 2101 |
|
| 2102 |
func magicCommentsChanged(original *ast.File, current *ast.File) bool { |
| 2103 |
oldComments := extractMagicComments(original) |
| 2104 |
newComments := extractMagicComments(current) |
| 2105 |
if len(oldComments) != len(newComments) { |
| 2106 |
return true |
| 2107 |
} |
| 2108 |
for i := range oldComments { |
| 2109 |
if oldComments[i] != newComments[i] { |
| 2110 |
return true |
| 2111 |
} |
| 2112 |
} |
| 2113 |
return false |
| 2114 |
} |
| 2115 |
|
| 2116 |
|
| 2117 |
func validImportPaths(imports []*ast.ImportSpec) map[string]struct{} { |
| 2118 |
m := make(map[string]struct{}) |
| 2119 |
for _, spec := range imports { |
| 2120 |
if path := spec.Path.Value; validImportPath(path) { |
| 2121 |
m[path] = struct{}{} |
| 2122 |
} |
| 2123 |
} |
| 2124 |
return m |
| 2125 |
} |
| 2126 |
|
| 2127 |
func validImportPath(path string) bool { |
| 2128 |
path, err := strconv.Unquote(path) |
| 2129 |
if err != nil { |
| 2130 |
return false |
| 2131 |
} |
| 2132 |
if path == "" { |
| 2133 |
return false |
| 2134 |
} |
| 2135 |
if path[len(path)-1] == '/' { |
| 2136 |
return false |
| 2137 |
} |
| 2138 |
return true |
| 2139 |
} |
| 2140 |
|
| 2141 |
var buildConstraintOrEmbedRe = regexp.MustCompile(`^//(go:embed|go:build|\s*\+build).*`) |
| 2142 |
|
| 2143 |
|
| 2144 |
func extractMagicComments(f *ast.File) []string { |
| 2145 |
var results []string |
| 2146 |
for _, cg := range f.Comments { |
| 2147 |
for _, c := range cg.List { |
| 2148 |
if buildConstraintOrEmbedRe.MatchString(c.Text) { |
| 2149 |
results = append(results, c.Text) |
| 2150 |
} |
| 2151 |
} |
| 2152 |
} |
| 2153 |
return results |
| 2154 |
} |
| 2155 |
|
| 2156 |
|
| 2157 |
|
| 2158 |
func (s *Snapshot) BuiltinFile(ctx context.Context) (*parsego.File, error) { |
| 2159 |
s.AwaitInitialized(ctx) |
| 2160 |
|
| 2161 |
s.mu.Lock() |
| 2162 |
builtin := s.builtin |
| 2163 |
s.mu.Unlock() |
| 2164 |
|
| 2165 |
if builtin == "" { |
| 2166 |
return nil, fmt.Errorf("no builtin package for view %s", s.view.folder.Name) |
| 2167 |
} |
| 2168 |
|
| 2169 |
fh, err := s.ReadFile(ctx, builtin) |
| 2170 |
if err != nil { |
| 2171 |
return nil, err |
| 2172 |
} |
| 2173 |
|
| 2174 |
|
| 2175 |
mode := parsego.Full &^ parser.SkipObjectResolution |
| 2176 |
pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), mode, false, fh) |
| 2177 |
if err != nil { |
| 2178 |
return nil, err |
| 2179 |
} |
| 2180 |
return pgfs[0], nil |
| 2181 |
} |
| 2182 |
|
| 2183 |
|
| 2184 |
func (s *Snapshot) IsBuiltin(uri protocol.DocumentURI) bool { |
| 2185 |
s.mu.Lock() |
| 2186 |
defer s.mu.Unlock() |
| 2187 |
|
| 2188 |
|
| 2189 |
return uri == s.builtin |
| 2190 |
} |
| 2191 |
|
| 2192 |
func (s *Snapshot) setBuiltin(path string) { |
| 2193 |
s.mu.Lock() |
| 2194 |
defer s.mu.Unlock() |
| 2195 |
|
| 2196 |
s.builtin = protocol.URIFromPath(path) |
| 2197 |
} |
| 2198 |
|
| 2199 |
|
| 2200 |
|
| 2201 |
func (s *Snapshot) WantCompilerOptDetails(dir protocol.DocumentURI) bool { |
| 2202 |
_, ok := s.compilerOptDetails[dir] |
| 2203 |
return ok |
| 2204 |
} |
| 2205 |
|
| 2206 |
|
| 2207 |
|
| 2208 |
type CodeLensSourceFunc func(context.Context, *Snapshot, file.Handle) ([]protocol.CodeLens, error) |