cache

package
v0.10.0-alpha.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2024 License: Apache-2.0 Imports: 78 Imported by: 0

Documentation

Overview

Package cache is the core of gopls: it is concerned with state management, dependency analysis, and invalidation; and it holds the machinery of type checking and modular static analysis. Its principal types are Session, Folder, View, Snapshot, Cache, and Package.

Index

Constants

View Source
const (
	ParseHeader = parsego.ParseHeader
	ParseFull   = parsego.ParseFull
)
View Source
const AnalysisProgressTitle = "Analyzing Dependencies"

AnalysisProgressTitle is the title of the progress report for ongoing analysis. It is sought by regression tests for the progress reporting feature.

Variables

View Source
var (
	KeyCreateSession   = NewSessionKey("create_session", "A new session was added")
	KeyUpdateSession   = NewSessionKey("update_session", "Updated information about a session")
	KeyShutdownSession = NewSessionKey("shutdown_session", "A session was shut down")
)
View Source
var ErrNoModOnDisk = errors.New("go.mod file is not on disk")

This error is sought by mod diagnostics.

View Source
var ErrViewExists = errors.New("view already exists for session")

TODO(rfindley): is the logic surrounding this error actually necessary?

Functions

func BuildLink(target, path, anchor string) string

BuildLink constructs a URL with the given target, path, and anchor.

func BundledQuickFixes

func BundledQuickFixes(diag protocol.Diagnostic) []protocol.CodeAction

BundledQuickFixes extracts any bundled codeActions from the diag.Data field.

func CheckPathValid

func CheckPathValid(dir string) error

CheckPathValid checks whether a directory is suitable as a workspace folder.

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

A Cache holds content that is shared across multiple gopls sessions.

func New

func New(store *memoize.Store) *Cache

New Creates a new cache for gopls operation results, using the given file set, shared store, and session options.

Both the fset and store may be nil, but if store is non-nil so must be fset (and they must always be used together), otherwise it may be possible to get cached data referencing token.Pos values not mapped by the FileSet.

func (*Cache) FileStats

func (c *Cache) FileStats() (stats command.FileStats)

FileStats returns information about the set of files stored in the cache. It is intended for debugging only.

func (*Cache) ID

func (c *Cache) ID() string

func (*Cache) MemStats

func (c *Cache) MemStats() map[reflect.Type]int

func (Cache) ReadFile

func (fs Cache) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error)

ReadFile stats and (maybe) reads the file, updates the cache, and returns it.

type Diagnostic

type Diagnostic struct {
	URI      protocol.DocumentURI // of diagnosed file (not diagnostic documentation)
	Range    protocol.Range
	Severity protocol.DiagnosticSeverity
	Code     string // analysis.Diagnostic.Category (or "default" if empty) or hidden go/types error code
	CodeHref string

	// Source is a human-readable description of the source of the error.
	// Diagnostics generated by an analysis.Analyzer set it to Analyzer.Name.
	Source DiagnosticSource

	Message string

	Tags    []protocol.DiagnosticTag
	Related []protocol.DiagnosticRelatedInformation

	// Fields below are used internally to generate quick fixes. They aren't
	// part of the LSP spec and historically didn't leave the server.
	//
	// Update(2023-05): version 3.16 of the LSP spec included support for the
	// Diagnostic.data field, which holds arbitrary data preserved in the
	// diagnostic for codeAction requests. This field allows bundling additional
	// information for quick-fixes, and gopls can (and should) use this
	// information to avoid re-evaluating diagnostics in code-action handlers.
	//
	// In order to stage this transition incrementally, the 'BundledFixes' field
	// may store a 'bundled' (=json-serialized) form of the associated
	// SuggestedFixes. Not all diagnostics have their fixes bundled.
	BundledFixes   *json.RawMessage
	SuggestedFixes []SuggestedFix
}

An Diagnostic corresponds to an LSP Diagnostic. https://microsoft.github.io/language-server-protocol/specification#diagnostic

It is (effectively) gob-serializable; see {encode,decode}Diagnostics.

func (*Diagnostic) String

func (d *Diagnostic) String() string

type DiagnosticSource

type DiagnosticSource string
const (
	UnknownError             DiagnosticSource = "<Unknown source>"
	ListError                DiagnosticSource = "go list"
	ParseError               DiagnosticSource = "syntax"
	TypeError                DiagnosticSource = "compiler"
	ModTidyError             DiagnosticSource = "go mod tidy"
	OptimizationDetailsError DiagnosticSource = "optimizer details"
	UpgradeNotification      DiagnosticSource = "upgrade available"
	Vulncheck                DiagnosticSource = "vulncheck imports"
	Govulncheck              DiagnosticSource = "govulncheck"
	TemplateError            DiagnosticSource = "template"
	WorkFileError            DiagnosticSource = "go.work file"
	ConsistencyInfo          DiagnosticSource = "consistency"
)

type Filterer

type Filterer struct {
	// contains filtered or unexported fields
}

func NewFilterer

func NewFilterer(rawFilters []string) *Filterer

NewFilterer computes regular expression form of all raw filters

func (*Filterer) Disallow

func (f *Filterer) Disallow(path string) bool

Disallow return true if the path is excluded from the filterer's filters.

type Folder

type Folder struct {
	Dir     protocol.DocumentURI
	Name    string // decorative name for UI; not necessarily unique
	Options *settings.Options
	Env     *GoEnv
}

A Folder represents an LSP workspace folder, together with its per-folder options and environment variables that affect build configuration.

Folders (Name and Dir) are specified by the 'initialize' and subsequent 'didChangeWorkspaceFolders' requests; their options come from didChangeConfiguration.

Folders must not be mutated, as they may be shared across multiple views.

type GoEnv

type GoEnv struct {
	// Go environment variables. These correspond directly with the Go env var of
	// the same name.
	GOOS        string
	GOARCH      string
	GOCACHE     string
	GOMODCACHE  string
	GOPATH      string
	GOPRIVATE   string
	GOFLAGS     string
	GO111MODULE string

	// Go version output.
	GoVersion       int    // The X in Go 1.X
	GoVersionOutput string // complete go version output

	// OS environment variables (notably not go env).
	GOWORK           string
	GOPACKAGESDRIVER string
}

GoEnv holds the environment variables and data from the Go command that is required for operating on a workspace folder.

func FetchGoEnv

func FetchGoEnv(ctx context.Context, folder protocol.DocumentURI, opts *settings.Options) (*GoEnv, error)

FetchGoEnv queries the environment and Go command to collect environment variables necessary for the workspace folder.

type ImportPath

type ImportPath = metadata.ImportPath

Convenient aliases for very heavily used types.

type InitializationError

type InitializationError struct {
	// MainError is the primary error. Must be non-nil.
	MainError error

	// Diagnostics contains any supplemental (structured) diagnostics extracted
	// from the load error.
	Diagnostics map[protocol.DocumentURI][]*Diagnostic
}

A InitializationError is an error that causes snapshot initialization to fail. It is either the error returned from go/packages.Load, or an error parsing a workspace go.work or go.mod file.

Such an error generally indicates that the View is malformed, and will never be usable.

type InvocationFlags

type InvocationFlags int

InvocationFlags represents the settings of a particular go command invocation. It is a mode, plus a set of flag bits.

const (
	// Normal is appropriate for commands that might be run by a user and don't
	// deliberately modify go.mod files, e.g. `go test`.
	Normal InvocationFlags = iota
	// WriteTemporaryModFile is for commands that need information from a
	// modified version of the user's go.mod file, e.g. `go mod tidy` used to
	// generate diagnostics.
	WriteTemporaryModFile
	// LoadWorkspace is for packages.Load, and other operations that should
	// consider the whole workspace at once.
	LoadWorkspace
	// AllowNetwork is a flag bit that indicates the invocation should be
	// allowed to access the network.
	AllowNetwork InvocationFlags = 1 << 10
)

func (InvocationFlags) AllowNetwork

func (m InvocationFlags) AllowNetwork() bool

func (InvocationFlags) Mode

type LabelDuration

type LabelDuration struct {
	Label    string
	Duration time.Duration
}

func AnalyzerRunTimes

func AnalyzerRunTimes() []LabelDuration

AnalyzerTimes returns the accumulated time spent in each Analyzer's Run function since process start, in descending order.

type Package

type Package struct {
	// contains filtered or unexported fields
}

A Package is the union of package metadata and type checking results.

TODO(rfindley): for now, we do not persist the post-processing of loadDiagnostics, because the value of the snapshot.packages map is just the package handle. Fix this.

func (*Package) CompiledGoFiles

func (p *Package) CompiledGoFiles() []*ParsedGoFile

func (*Package) DependencyTypes

func (p *Package) DependencyTypes(path PackagePath) *types.Package

DependencyTypes returns the type checker's symbol for the specified package. It returns nil if path is not among the transitive dependencies of p, or if no symbols from that package were referenced during the type-checking of p.

func (*Package) File

func (p *Package) File(uri protocol.DocumentURI) (*ParsedGoFile, error)

func (*Package) FileSet

func (p *Package) FileSet() *token.FileSet

func (*Package) GetParseErrors

func (p *Package) GetParseErrors() []scanner.ErrorList

func (*Package) GetSyntax

func (p *Package) GetSyntax() []*ast.File

func (*Package) GetTypeErrors

func (p *Package) GetTypeErrors() []types.Error

func (*Package) GetTypes

func (p *Package) GetTypes() *types.Package

func (*Package) GetTypesInfo

func (p *Package) GetTypesInfo() *types.Info

func (*Package) Metadata

func (p *Package) Metadata() *metadata.Package

func (*Package) String

func (p *Package) String() string

type PackageID

type PackageID = metadata.PackageID

Convenient aliases for very heavily used types.

type PackageName

type PackageName = metadata.PackageName

Convenient aliases for very heavily used types.

type PackagePath

type PackagePath = metadata.PackagePath

Convenient aliases for very heavily used types.

type ParsedGoFile

type ParsedGoFile = parsego.File

Convenient aliases for very heavily used types.

type ParsedModule

type ParsedModule struct {
	URI         protocol.DocumentURI
	File        *modfile.File
	Mapper      *protocol.Mapper
	ParseErrors []*Diagnostic
}

A ParsedModule contains the results of parsing a go.mod file.

type ParsedWorkFile

type ParsedWorkFile struct {
	URI         protocol.DocumentURI
	File        *modfile.WorkFile
	Mapper      *protocol.Mapper
	ParseErrors []*Diagnostic
}

A ParsedWorkFile contains the results of parsing a go.work file.

type Session

type Session struct {
	// contains filtered or unexported fields
}

A Session holds the state (views, file contents, parse cache, memoized computations) of a gopls server process.

It implements the file.Source interface.

func NewSession

func NewSession(ctx context.Context, c *Cache) *Session

NewSession creates a new gopls session with the given cache.

func (*Session) Cache

func (s *Session) Cache() *Cache

Cache returns the cache that created this session, for debugging only.

func (*Session) DidModifyFiles

func (s *Session) DidModifyFiles(ctx context.Context, modifications []file.Modification) (map[*View][]protocol.DocumentURI, error)

DidModifyFiles reports a file modification to the session. It returns the new snapshots after the modifications have been applied, paired with the affected file URIs for those snapshots. On success, it returns a release function that must be called when the snapshots are no longer needed.

TODO(rfindley): what happens if this function fails? It must leave us in a broken state, which we should surface to the user, probably as a request to restart gopls.

func (*Session) ExpandModificationsToDirectories

func (s *Session) ExpandModificationsToDirectories(ctx context.Context, changes []file.Modification) []file.Modification

ExpandModificationsToDirectories returns the set of changes with the directory changes removed and expanded to include all of the files in the directory.

func (*Session) FileWatchingGlobPatterns

func (s *Session) FileWatchingGlobPatterns(ctx context.Context) map[protocol.RelativePattern]unit

FileWatchingGlobPatterns returns a set of glob patterns that the client is required to watch for changes, and notify the server of them, in order to keep the server's state up to date.

This set includes

  1. all go.mod and go.work files in the workspace; and
  2. for each Snapshot, its modules (or directory for ad-hoc views). In module mode, this is the set of active modules (and for VS Code, all workspace directories within them, due to golang/go#42348).

The watch for workspace go.work and go.mod files in (1) is sufficient to capture changes to the repo structure that may affect the set of views. Whenever this set changes, we reload the workspace and invalidate memoized files.

The watch for workspace directories in (2) should keep each View up to date, as it should capture any newly added/modified/deleted Go files.

Patterns are returned as a set of protocol.RelativePatterns, since they can always be later translated to glob patterns (i.e. strings) if the client lacks relative pattern support. By convention, any pattern returned with empty baseURI should be served as a glob pattern.

In general, we prefer to serve relative patterns, as they work better on most clients that support both, and do not have issues with Windows driver letter casing: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#relativePattern

TODO(golang/go#57979): we need to reset the memoizedFS when a view changes. Consider the case where we incidentally read a file, then it moved outside of an active module, and subsequently changed: we would still observe the original file state.

func (*Session) GoCommandRunner

func (s *Session) GoCommandRunner() *gocommand.Runner

GoCommandRunner returns the gocommand Runner for this session.

func (*Session) ID

func (s *Session) ID() string

ID returns the unique identifier for this session on this server.

func (*Session) InvalidateView

func (s *Session) InvalidateView(ctx context.Context, view *View, changed StateChange) (*Snapshot, func(), error)

InvalidateView processes the provided state change, invalidating any derived results that depend on the changed state.

The resulting snapshot is non-nil, representing the outcome of the state change. The second result is a function that must be called to release the snapshot when the snapshot is no longer needed.

An error is returned if the given view is no longer active in the session.

func (*Session) NewView

func (s *Session) NewView(ctx context.Context, folder *Folder) (*View, *Snapshot, func(), error)

NewView creates a new View, returning it and its first snapshot. If a non-empty tempWorkspace directory is provided, the View will record a copy of its gopls workspace module in that directory, so that client tooling can execute in the same main module. On success it also returns a release function that must be called when the Snapshot is no longer needed.

func (*Session) OrphanedFileDiagnostics

func (s *Session) OrphanedFileDiagnostics(ctx context.Context) (map[protocol.DocumentURI][]*Diagnostic, error)

OrphanedFileDiagnostics reports diagnostics describing why open files have no packages or have only command-line-arguments packages.

If the resulting diagnostic is nil, the file is either not orphaned or we can't produce a good diagnostic.

The caller must not mutate the result.

func (Session) Overlays

func (fs Session) Overlays() []*overlay

Overlays returns a new unordered array of overlays.

func (Session) ReadFile

func (fs Session) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error)

func (*Session) RemoveView

func (s *Session) RemoveView(dir protocol.DocumentURI) bool

RemoveView removes from the session the view rooted at the specified directory. It reports whether a view of that directory was removed.

func (*Session) ResetView

func (s *Session) ResetView(ctx context.Context, uri protocol.DocumentURI) (*View, error)

ResetView resets the best view for the given URI.

func (*Session) Shutdown

func (s *Session) Shutdown(ctx context.Context)

Shutdown the session and all views it has created.

func (*Session) SnapshotOf

func (s *Session) SnapshotOf(ctx context.Context, uri protocol.DocumentURI) (*Snapshot, func(), error)

SnapshotOf returns a Snapshot corresponding to the given URI.

In the case where the file can be can be associated with a View by bestViewForURI (based on directory information alone, without package metadata), SnapshotOf returns the current Snapshot for that View. Otherwise, it awaits loading package metadata and returns a Snapshot for the first View containing a real (=not command-line-arguments) package for the file.

If that also fails to find a View, SnapshotOf returns a Snapshot for the first view in s.views that is not shut down (i.e. s.views[0] unless we lose a race), for determinism in tests and so that we tend to aggregate the resulting command-line-arguments packages into a single view.

SnapshotOf returns an error if a failure occurs along the way (most likely due to context cancellation), or if there are no Views in the Session.

On success, the caller must call the returned function to release the snapshot.

func (*Session) String

func (s *Session) String() string

func (*Session) UpdateFolders

func (s *Session) UpdateFolders(ctx context.Context, newFolders []*Folder) error

UpdateFolders updates the set of views for the new folders.

Calling this causes each view to be reinitialized.

func (*Session) View

func (s *Session) View(id string) (*View, error)

View returns the view with a matching id, if present.

func (*Session) Views

func (s *Session) Views() []*View

type SessionKey

type SessionKey struct {
	// contains filtered or unexported fields
}

SessionKey represents an event label key that has a *Session value.

func NewSessionKey

func NewSessionKey(name, description string) *SessionKey

NewSessionKey creates a new Key for *Session values.

func (*SessionKey) Description

func (k *SessionKey) Description() string

func (*SessionKey) Format

func (k *SessionKey) Format(w io.Writer, buf []byte, l label.Label)

func (*SessionKey) From

func (k *SessionKey) From(t label.Label) *Session

From can be used to get the session value from a Label.

func (*SessionKey) Get

func (k *SessionKey) Get(lm label.Map) *Session

Get can be used to get the session for the key from a label.Map.

func (*SessionKey) Name

func (k *SessionKey) Name() string

func (*SessionKey) Of

func (k *SessionKey) Of(v *Session) label.Label

Of creates a new Label with this key and the supplied session.

type Snapshot

type Snapshot struct {
	// contains filtered or unexported fields
}

A Snapshot represents the current state for a given view.

It is first and foremost an idempotent implementation of file.Source whose ReadFile method returns consistent information about the existence and content of each file throughout its lifetime.

However, the snapshot also manages additional state (such as parsed files and packages) that are derived from file content.

Snapshots are responsible for bookkeeping and invalidation of this state, implemented in Snapshot.clone.

func (*Snapshot) Acquire

func (s *Snapshot) Acquire() func()

Acquire prevents the snapshot from being destroyed until the returned function is called.

(s.Acquire().release() could instead be expressed as a pair of method calls s.IncRef(); s.DecRef(). The latter has the advantage that the DecRefs are fungible and don't require holding anything in addition to the refcounted object s, but paradoxically that is also an advantage of the current approach, which forces the caller to consider the release function at every stage, making a reference leak more obvious.)

func (*Snapshot) AllMetadata

func (s *Snapshot) AllMetadata(ctx context.Context) ([]*metadata.Package, error)

AllMetadata returns a new unordered array of metadata for all packages known to this snapshot, which includes the packages of all workspace modules plus their transitive import dependencies.

It may also contain ad-hoc packages for standalone files. It includes all test variants.

TODO(rfindley): Replace this with s.MetadataGraph().

func (*Snapshot) Analyze

func (s *Snapshot) Analyze(ctx context.Context, pkgs map[PackageID]*metadata.Package, analyzers []*settings.Analyzer, reporter *progress.Tracker) ([]*Diagnostic, error)

Analyze applies a set of analyzers to the package denoted by id, and returns their diagnostics for that package.

The analyzers list must be duplicate free; order does not matter.

Notifications of progress may be sent to the optional reporter.

func (*Snapshot) AwaitInitialized

func (s *Snapshot) AwaitInitialized(ctx context.Context)

AwaitInitialized waits until the snapshot's view is initialized.

func (*Snapshot) BackgroundContext

func (s *Snapshot) BackgroundContext() context.Context

BackgroundContext returns a context used for all background processing on behalf of this snapshot.

func (*Snapshot) BuiltinFile

func (s *Snapshot) BuiltinFile(ctx context.Context) (*ParsedGoFile, error)

BuiltinFile returns information about the special builtin package.

func (*Snapshot) FileKind

func (s *Snapshot) FileKind(fh file.Handle) file.Kind

FileKind returns the kind of a file.

We can't reliably deduce the kind from the file name alone, as some editors can be told to interpret a buffer as language different from the file name heuristic, e.g. that an .html file actually contains Go "html/template" syntax, or even that a .go file contains Python.

func (*Snapshot) FindFile

func (s *Snapshot) FindFile(uri protocol.DocumentURI) file.Handle

FindFile returns the FileHandle for the given URI, if it is already in the given snapshot. TODO(adonovan): delete this operation; use ReadFile instead.

func (*Snapshot) Folder

func (s *Snapshot) Folder() protocol.DocumentURI

Folder returns the folder at the base of this snapshot.

func (*Snapshot) GoModForFile

func (s *Snapshot) GoModForFile(uri protocol.DocumentURI) protocol.DocumentURI

GoModForFile returns the URI of the go.mod file for the given URI.

TODO(rfindley): clarify that this is only active modules. Or update to just use findRootPattern.

func (*Snapshot) GoVersionString

func (s *Snapshot) GoVersionString() string

GoVersionString is temporarily available from the snapshot.

TODO(rfindley): refactor so that this method is not necessary.

func (*Snapshot) IgnoredFile

func (s *Snapshot) IgnoredFile(uri protocol.DocumentURI) bool

IgnoredFile reports if a file would be ignored by a `go list` of the whole workspace.

While go list ./... skips directories starting with '.', '_', or 'testdata', gopls may still load them via file queries. Explicitly filter them out.

func (*Snapshot) InitializationError

func (s *Snapshot) InitializationError() *InitializationError

InitializationError returns the last error from initialization.

func (*Snapshot) IsBuiltin

func (s *Snapshot) IsBuiltin(uri protocol.DocumentURI) bool

IsBuiltin reports whether uri is part of the builtin package.

func (*Snapshot) IsGoPrivatePath

func (s *Snapshot) IsGoPrivatePath(target string) bool

IsGoPrivatePath reports whether target is a private import path, as identified by the GOPRIVATE environment variable.

func (*Snapshot) IsOpen

func (s *Snapshot) IsOpen(uri protocol.DocumentURI) bool

IsOpen returns whether the editor currently has a file open.

func (*Snapshot) Labels

func (s *Snapshot) Labels() []label.Label

SnapshotLabels returns a new slice of labels that should be used for events related to a snapshot.

func (*Snapshot) Metadata

func (s *Snapshot) Metadata(id PackageID) *metadata.Package

Metadata returns the metadata for the specified package, or nil if it was not found.

func (*Snapshot) MetadataForFile

func (s *Snapshot) MetadataForFile(ctx context.Context, uri protocol.DocumentURI) ([]*metadata.Package, error)

MetadataForFile returns a new slice containing metadata for each package containing the Go file identified by uri, ordered by the number of CompiledGoFiles (i.e. "narrowest" to "widest" package), and secondarily by IsIntermediateTestVariant (false < true). The result may include tests and intermediate test variants of importable packages. It returns an error if the context was cancelled.

func (*Snapshot) MetadataGraph

func (s *Snapshot) MetadataGraph() *metadata.Graph

MetadataGraph returns the current metadata graph for the Snapshot.

func (*Snapshot) MethodSets

func (s *Snapshot) MethodSets(ctx context.Context, ids ...PackageID) ([]*methodsets.Index, error)

MethodSets returns method-set indexes for the specified packages.

If these indexes cannot be loaded from cache, the requested packages may be type-checked.

func (*Snapshot) ModTidy

func (s *Snapshot) ModTidy(ctx context.Context, pm *ParsedModule) (*TidiedModule, error)

ModTidy returns the go.mod file that would be obtained by running "go mod tidy". Concurrent requests are combined into a single command.

func (*Snapshot) ModWhy

func (s *Snapshot) ModWhy(ctx context.Context, fh file.Handle) (map[string]string, error)

ModWhy returns the "go mod why" result for each module named in a require statement in the go.mod file. TODO(adonovan): move to new mod_why.go file.

func (*Snapshot) ModuleUpgrades

func (s *Snapshot) ModuleUpgrades(modfile protocol.DocumentURI) map[string]string

ModuleUpgrades returns known module upgrades for the dependencies of modfile.

func (*Snapshot) Options

func (s *Snapshot) Options() *settings.Options

Options returns the options associated with this snapshot.

func (*Snapshot) Overlays

func (s *Snapshot) Overlays() []*overlay

Overlays returns the set of overlays at this snapshot.

Note that this may differ from the set of overlays on the server, if the snapshot observed a historical state.

func (*Snapshot) PackageDiagnostics

func (s *Snapshot) PackageDiagnostics(ctx context.Context, ids ...PackageID) (map[protocol.DocumentURI][]*Diagnostic, error)

PackageDiagnostics returns diagnostics for files contained in specified packages.

If these diagnostics cannot be loaded from cache, the requested packages may be type-checked.

func (*Snapshot) ParseGo

func (s *Snapshot) ParseGo(ctx context.Context, fh file.Handle, mode parser.Mode) (*ParsedGoFile, error)

ParseGo parses the file whose contents are provided by fh. The resulting tree may have been fixed up. If the file is not available, returns nil and an error.

func (*Snapshot) ParseMod

func (s *Snapshot) ParseMod(ctx context.Context, fh file.Handle) (*ParsedModule, error)

ParseMod parses a go.mod file, using a cache. It may return partial results and an error.

func (*Snapshot) ParseWork

func (s *Snapshot) ParseWork(ctx context.Context, fh file.Handle) (*ParsedWorkFile, error)

ParseWork parses a go.work file, using a cache. It may return partial results and an error. TODO(adonovan): move to new work.go file.

func (*Snapshot) ReadFile

func (s *Snapshot) ReadFile(ctx context.Context, uri protocol.DocumentURI) (file.Handle, error)

ReadFile returns a File for the given URI. If the file is unknown it is added to the managed set.

ReadFile succeeds even if the file does not exist. A non-nil error return indicates some type of internal error, for example if ctx is cancelled.

func (*Snapshot) References

func (s *Snapshot) References(ctx context.Context, ids ...PackageID) ([]xrefIndex, error)

References returns cross-reference indexes for the specified packages.

If these indexes cannot be loaded from cache, the requested packages may be type-checked.

func (*Snapshot) ReverseDependencies

func (s *Snapshot) ReverseDependencies(ctx context.Context, id PackageID, transitive bool) (map[PackageID]*metadata.Package, error)

ReverseDependencies returns a new mapping whose entries are the ID and Metadata of each package in the workspace that directly or transitively depend on the package denoted by id, excluding id itself.

func (*Snapshot) RunGoCommandDirect

func (s *Snapshot) RunGoCommandDirect(ctx context.Context, mode InvocationFlags, inv *gocommand.Invocation) (*bytes.Buffer, error)

RunGoCommandDirect runs the given `go` command. Verb, Args, and WorkingDir must be specified.

func (*Snapshot) RunGoCommandPiped

func (s *Snapshot) RunGoCommandPiped(ctx context.Context, mode InvocationFlags, inv *gocommand.Invocation, stdout, stderr io.Writer) error

RunGoCommandPiped runs the given `go` command, writing its output to stdout and stderr. Verb, Args, and WorkingDir must be specified.

RunGoCommandPiped runs the command serially using gocommand.RunPiped, enforcing that this command executes exclusively to other commands on the server.

func (*Snapshot) RunGoModUpdateCommands

func (s *Snapshot) RunGoModUpdateCommands(ctx context.Context, wd string, run func(invoke func(...string) (*bytes.Buffer, error)) error) ([]byte, []byte, error)

RunGoModUpdateCommands runs a series of `go` commands that updates the go.mod and go.sum file for wd, and returns their updated contents.

TODO(rfindley): the signature of RunGoModUpdateCommands is very confusing. Simplify it.

func (*Snapshot) RunProcessEnvFunc

func (s *Snapshot) RunProcessEnvFunc(ctx context.Context, fn func(context.Context, *imports.Options) error) error

RunProcessEnvFunc runs fn with the process env for this snapshot's view. Note: the process env contains cached module and filesystem state.

func (*Snapshot) SequenceID

func (s *Snapshot) SequenceID() uint64

SequenceID is the sequence id of this snapshot within its containing view.

Relative to their view sequence ids are monotonically increasing, but this does not hold globally: when new views are created their initial snapshot has sequence ID 0.

func (*Snapshot) Symbols

func (s *Snapshot) Symbols(ctx context.Context, workspaceOnly bool) (map[protocol.DocumentURI][]Symbol, error)

Symbols extracts and returns symbol information for every file contained in a loaded package. It awaits snapshot loading.

If workspaceOnly is set, this only includes symbols from files in a workspace package. Otherwise, it returns symbols from all loaded packages.

TODO(rfindley): move to symbols.go.

func (*Snapshot) Templates

func (s *Snapshot) Templates() map[protocol.DocumentURI]file.Handle

Templates returns the .tmpl files.

func (*Snapshot) TypeCheck

func (s *Snapshot) TypeCheck(ctx context.Context, ids ...PackageID) ([]*Package, error)

TypeCheck parses and type-checks the specified packages, and returns them in the same order as the ids. The resulting packages' types may belong to different importers, so types from different packages are incommensurable.

The resulting packages slice always contains len(ids) entries, though some of them may be nil if (and only if) the resulting error is non-nil.

An error is returned if any of the requested packages fail to type-check. This is different from having type-checking errors: a failure to type-check indicates context cancellation or otherwise significant failure to perform the type-checking operation.

In general, clients should never need to type-checked syntax for an intermediate test variant (ITV) package. Callers should apply RemoveIntermediateTestVariants (or equivalent) before this method, or any of the potentially type-checking methods below.

func (*Snapshot) View

func (s *Snapshot) View() *View

View returns the View associated with this snapshot.

func (*Snapshot) WantGCDetails

func (s *Snapshot) WantGCDetails(id metadata.PackageID) bool

WantGCDetails reports whether to compute GC optimization details for the specified package.

func (*Snapshot) WorkspaceMetadata

func (s *Snapshot) WorkspaceMetadata(ctx context.Context) ([]*metadata.Package, error)

WorkspaceMetadata returns a new, unordered slice containing metadata for all ordinary and test packages (but not intermediate test variants) in the workspace.

The workspace is the set of modules typically defined by a go.work file. It is not transitively closed: for example, the standard library is not usually part of the workspace even though every module in the workspace depends on it.

Operations that must inspect all the dependencies of the workspace packages should instead use AllMetadata.

type StateChange

type StateChange struct {
	Modifications  []file.Modification // if set, the raw modifications originating this change
	Files          map[protocol.DocumentURI]file.Handle
	ModuleUpgrades map[protocol.DocumentURI]map[string]string
	GCDetails      map[metadata.PackageID]bool // package -> whether or not we want details
}

A StateChange describes external state changes that may affect a snapshot.

By far the most common of these is a change to file state, but a query of module upgrade information or vulnerabilities also affects gopls' behavior.

type SuggestedFix

type SuggestedFix struct {
	Title      string
	Edits      map[protocol.DocumentURI][]protocol.TextEdit
	Command    *protocol.Command
	ActionKind protocol.CodeActionKind
}

A SuggestedFix represents a suggested fix (for a diagnostic) produced by analysis, in protocol form.

The fixes are reported to the client as a set of code actions in response to a CodeAction query for a set of diagnostics. Multiple SuggestedFixes may be produced for the same logical fix, varying only in ActionKind. For example, a fix may be both a Refactor (which should appear on the refactoring menu) and a SourceFixAll (a clear fix that can be safely applied without explicit consent).

func SuggestedFixFromCommand

func SuggestedFixFromCommand(cmd protocol.Command, kind protocol.CodeActionKind) SuggestedFix

SuggestedFixFromCommand returns a suggested fix to run the given command.

type Symbol

type Symbol struct {
	Name  string
	Kind  protocol.SymbolKind
	Range protocol.Range
}

Symbol holds a precomputed symbol value. Note: we avoid using the protocol.SymbolInformation struct here in order to reduce the size of each symbol.

type TidiedModule

type TidiedModule struct {
	// Diagnostics representing changes made by `go mod tidy`.
	Diagnostics []*Diagnostic
	// The bytes of the go.mod file after it was tidied.
	TidiedContent []byte
}

A TidiedModule contains the results of running `go mod tidy` on a module.

type View

type View struct {
	// contains filtered or unexported fields
}

View represents a single build for a workspace.

A View is a logical build (the viewDefinition) along with a state of that build (the Snapshot).

func (View) EnvOverlay

func (d View) EnvOverlay() []string

EnvOverlay returns a new sorted slice of environment variables (in the form "k=v") for this view definition's env overlay.

func (*View) Folder

func (v *View) Folder() *Folder

Folder returns the folder at the base of this view.

func (View) GOARCH

func (d View) GOARCH() string

GOOS returns the effective GOARCH value for this view definition, accounting for its env overlay.

func (View) GOOS

func (d View) GOOS() string

GOOS returns the effective GOOS value for this view definition, accounting for its env overlay.

func (View) GoMod

func (d View) GoMod() protocol.DocumentURI

GoMod returns the nearest go.mod file for this view's root, or "".

func (*View) GoVersion

func (v *View) GoVersion() int

GoVersion returns the effective release Go version (the X in go1.X) for this view.

func (*View) GoVersionString

func (v *View) GoVersionString() string

GoVersionString returns the effective Go version string for this view.

Unlike [GoVersion], this encodes the minor version and commit hash information.

func (View) GoWork

func (d View) GoWork() protocol.DocumentURI

GoWork returns the nearest go.work file for this view's root, or "".

func (*View) ID

func (v *View) ID() string

func (View) ModFiles

func (d View) ModFiles() []protocol.DocumentURI

ModFiles are the go.mod files enclosed in the snapshot's view and known to the snapshot.

func (View) Root

func (d View) Root() protocol.DocumentURI

Root returns the view root, which determines where packages are loaded from.

func (*View) Snapshot

func (v *View) Snapshot() (*Snapshot, func(), error)

Snapshot returns the current snapshot for the view, and a release function that must be called when the Snapshot is no longer needed.

The resulting error is non-nil if and only if the view is shut down, in which case the resulting release function will also be nil.

func (View) Type

func (d View) Type() ViewType

Type returns the ViewType type, which determines how go/packages are loaded for this View.

type ViewType

type ViewType int

A ViewType describes how we load package information for a view.

This is used for constructing the go/packages.Load query, and for interpreting missing packages, imports, or errors.

See the documentation for individual ViewType values for details.

const (
	// GoPackagesDriverView is a view with a non-empty GOPACKAGESDRIVER
	// environment variable.
	//
	// Load: ./... from the workspace folder.
	GoPackagesDriverView ViewType = iota

	// GOPATHView is a view in GOPATH mode.
	//
	// I.e. in GOPATH, with GO111MODULE=off, or GO111MODULE=auto with no
	// go.mod file.
	//
	// Load: ./... from the workspace folder.
	GOPATHView

	// GoModView is a view in module mode with a single Go module.
	//
	// Load: <modulePath>/... from the module root.
	GoModView

	// GoWorkView is a view in module mode with a go.work file.
	//
	// Load: <modulePath>/... from the workspace folder, for each module.
	GoWorkView

	// An AdHocView is a collection of files in a given directory, not in GOPATH
	// or a module.
	//
	// Load: . from the workspace folder.
	AdHocView
)

func (ViewType) String

func (t ViewType) String() string

Directories

Path Synopsis
The metadata package defines types and functions for working with package metadata, which describes Go packages and their relationships.
The metadata package defines types and functions for working with package metadata, which describes Go packages and their relationships.
Package methodsets defines an incremental, serializable index of method-set information that allows efficient 'implements' queries across packages of the workspace without using the type checker.
Package methodsets defines an incremental, serializable index of method-set information that allows efficient 'implements' queries across packages of the workspace without using the type checker.
Package typerefs extracts symbol-level reachability information from the syntax of a Go package.
Package typerefs extracts symbol-level reachability information from the syntax of a Go package.
Package xrefs defines the serializable index of cross-package references that is computed during type checking.
Package xrefs defines the serializable index of cross-package references that is computed during type checking.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL