golang

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2024 License: BSD-3-Clause Imports: 78 Imported by: 0

Documentation

Overview

Package golang defines the LSP features for navigation, analysis, and refactoring of Go source code.

Index

Constants

View Source
const (
	ParameterNames             = "parameterNames"
	AssignVariableTypes        = "assignVariableTypes"
	ConstantValues             = "constantValues"
	RangeVariableTypes         = "rangeVariableTypes"
	CompositeLiteralTypes      = "compositeLiteralTypes"
	CompositeLiteralFieldNames = "compositeLiteralFields"
	FunctionTypeParameters     = "functionTypeParameters"
)

Variables

View Source
var AllInlayHints = map[string]*Hint{
	AssignVariableTypes: {
		Name: AssignVariableTypes,
		Doc:  "Enable/disable inlay hints for variable types in assign statements:\n```go\n\ti/* int*/, j/* int*/ := 0, len(r)-1\n```",
		Run:  assignVariableTypes,
	},
	ParameterNames: {
		Name: ParameterNames,
		Doc:  "Enable/disable inlay hints for parameter names:\n```go\n\tparseInt(/* str: */ \"123\", /* radix: */ 8)\n```",
		Run:  parameterNames,
	},
	ConstantValues: {
		Name: ConstantValues,
		Doc:  "Enable/disable inlay hints for constant values:\n```go\n\tconst (\n\t\tKindNone   Kind = iota/* = 0*/\n\t\tKindPrint/*  = 1*/\n\t\tKindPrintf/* = 2*/\n\t\tKindErrorf/* = 3*/\n\t)\n```",
		Run:  constantValues,
	},
	RangeVariableTypes: {
		Name: RangeVariableTypes,
		Doc:  "Enable/disable inlay hints for variable types in range statements:\n```go\n\tfor k/* int*/, v/* string*/ := range []string{} {\n\t\tfmt.Println(k, v)\n\t}\n```",
		Run:  rangeVariableTypes,
	},
	CompositeLiteralTypes: {
		Name: CompositeLiteralTypes,
		Doc:  "Enable/disable inlay hints for composite literal types:\n```go\n\tfor _, c := range []struct {\n\t\tin, want string\n\t}{\n\t\t/*struct{ in string; want string }*/{\"Hello, world\", \"dlrow ,olleH\"},\n\t}\n```",
		Run:  compositeLiteralTypes,
	},
	CompositeLiteralFieldNames: {
		Name: CompositeLiteralFieldNames,
		Doc:  "Enable/disable inlay hints for composite literal field names:\n```go\n\t{/*in: */\"Hello, world\", /*want: */\"dlrow ,olleH\"}\n```",
		Run:  compositeLiteralFields,
	},
	FunctionTypeParameters: {
		Name: FunctionTypeParameters,
		Doc:  "Enable/disable inlay hints for implicit type parameters on generic functions:\n```go\n\tmyFoo/*[int, string]*/(1, \"hello\")\n```",
		Run:  funcTypeParams,
	},
}

AllInlayHints describes the various inlay-hints options.

It is the source from which gopls/doc/inlayHints.md is generated.

View Source
var ErrNoEmbed = errors.New("no embed directive found")

ErrNoEmbed is returned by EmbedDefinition when no embed directive is found at a particular position. As such it indicates that other definitions could be worth checking.

View Source
var ErrNoIdentFound = errors.New("no identifier found")

ErrNoIdentFound is error returned when no identifier is found at a particular position

View Source
var ErrNoLinkname = errors.New("no linkname directive found")

ErrNoLinkname is returned by LinknameDefinition when no linkname directive is found at a particular position. As such it indicates that other definitions could be worth checking.

Functions

func AddImport

func AddImport(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, importPath string) ([]protocol.TextEdit, error)

AddImport adds a single import statement to the given file

func Analyze

func Analyze(ctx context.Context, snapshot *cache.Snapshot, pkgIDs map[PackageID]*metadata.Package, tracker *progress.Tracker) (map[protocol.DocumentURI][]*cache.Diagnostic, error)

Analyze reports go/analysis-framework diagnostics in the specified package.

If the provided tracker is non-nil, it may be used to provide notifications of the ongoing analysis pass.

TODO(rfindley): merge this with snapshot.Analyze.

func ApplyFix

func ApplyFix(ctx context.Context, fix string, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.DocumentChange, error)

ApplyFix applies the specified kind of suggested fix to the given file and range, returning the resulting changes.

A fix kind is either the Category of an analysis.Diagnostic that had a SuggestedFix with no edits; or the name of a fix agreed upon by CodeActions and this function. Fix kinds identify fixes in the command protocol.

TODO(adonovan): come up with a better mechanism for registering the connection between analyzers, code actions, and fixers. A flaw of the current approach is that the same Category could in theory apply to a Diagnostic with several lazy fixes, making them impossible to distinguish. It would more precise if there was a SuggestedFix.Category field, or some other way to squirrel metadata in the fix.

func AssemblyHTML added in v0.16.0

func AssemblyHTML(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, symbol string, web Web) ([]byte, error)

AssemblyHTML returns an HTML document containing an assembly listing of the selected function.

TODO(adonovan): - display a "Compiling..." message as a cold build can be slow. - cross-link jumps and block labels, like github.com/aclements/objbrowse.

func CodeActions

func CodeActions(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range, diagnostics []protocol.Diagnostic, want map[protocol.CodeActionKind]bool, trigger protocol.CodeActionTriggerKind) (actions []protocol.CodeAction, _ error)

CodeActions returns all wanted code actions (edits and other commands) available for the selected range.

Depending on how the request was triggered, fewer actions may be offered, e.g. to avoid UI distractions after mere cursor motion.

See ../protocol/codeactionkind.go for some code action theory.

func CodeLensSources added in v0.16.0

func CodeLensSources() map[settings.CodeLensSource]cache.CodeLensSourceFunc

CodeLensSources returns the supported sources of code lenses for Go files.

func CollectScopes

func CollectScopes(info *types.Info, path []ast.Node, pos token.Pos) []*types.Scope

CollectScopes returns all scopes in an ast path, ordered as innermost scope first.

func CommentToMarkdown

func CommentToMarkdown(text string, options *settings.Options) string

CommentToMarkdown converts comment text to formatted markdown. The comment was prepared by DocReader, so it is known not to have leading, trailing blank lines nor to have trailing spaces at the end of lines. The comment markers have already been removed.

func ComputeOneImportFixEdits

func ComputeOneImportFixEdits(snapshot *cache.Snapshot, pgf *parsego.File, fix *imports.ImportFix) ([]protocol.TextEdit, error)

ComputeOneImportFixEdits returns text edits for a single import fix.

func Definition

func Definition(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) ([]protocol.Location, error)

Definition handles the textDocument/definition request for Go files.

func DocumentSymbols

func DocumentSymbols(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.DocumentSymbol, error)

func Format

func Format(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.TextEdit, error)

Format formats a file with a given range.

func FormatNode

func FormatNode(fset *token.FileSet, n ast.Node) string

FormatNode returns the "pretty-print" output for an ast node.

func FormatType

func FormatType(typ types.Type, qf types.Qualifier) (detail string, kind protocol.CompletionItemKind)

FormatType returns the detail and kind for a types.Type.

func FormatTypeParams

func FormatTypeParams(tparams *types.TypeParamList) string

FormatTypeParams turns TypeParamList into its Go representation, such as: [T, Y]. Note that it does not print constraints as this is mainly used for formatting type params in method receivers.

func FormatVarType

func FormatVarType(ctx context.Context, snapshot *cache.Snapshot, srcpkg *cache.Package, obj *types.Var, qf types.Qualifier, mq MetadataQualifier) (string, error)

FormatVarType formats a *types.Var, accounting for type aliases. To do this, it looks in the AST of the file in which the object is declared. On any errors, it always falls back to types.TypeString.

TODO(rfindley): this function could return the actual name used in syntax, for better parameter names.

func FreeSymbolsHTML added in v0.16.0

func FreeSymbolsHTML(viewID string, pkg *cache.Package, pgf *parsego.File, start, end token.Pos, web Web) []byte

FreeSymbolsHTML returns an HTML document containing the report of free symbols referenced by the selection.

func GCOptimizationDetails

func GCOptimizationDetails(ctx context.Context, snapshot *cache.Snapshot, mp *metadata.Package) (map[protocol.DocumentURI][]*cache.Diagnostic, error)

GCOptimizationDetails invokes the Go compiler on the specified package and reports its log of optimizations decisions as a set of diagnostics.

TODO(adonovan): this feature needs more consistent and informative naming. Now that the compiler is cmd/compile, "GC" now means only "garbage collection". I propose "(Toggle|Display) Go compiler optimization details" in the UI, and CompilerOptimizationDetails for this function and compileropts.go for the file.

func Highlight

func Highlight(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) ([]protocol.Range, error)

func Hover

func Hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position, pkgURL func(path PackagePath, fragment string) protocol.URI) (*protocol.Hover, error)

Hover implements the "textDocument/hover" RPC for Go files. It may return nil even on success.

If pkgURL is non-nil, it should be used to generate doc links.

func HoverDocForObject

func HoverDocForObject(ctx context.Context, snapshot *cache.Snapshot, fset *token.FileSet, obj types.Object) (*ast.CommentGroup, error)

HoverDocForObject returns the best doc comment for obj (for which fset provides file/line information).

TODO(rfindley): there appears to be zero(!) tests for this functionality.

func Implementation

func Implementation(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, pp protocol.Position) ([]protocol.Location, error)

Implementation returns a new sorted array of locations of declarations of types that implement (or are implemented by) the type referred to at the given position.

If the position denotes a method, the computation is applied to its receiver type and then its corresponding methods are returned.

func IncomingCalls

func IncomingCalls(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pos protocol.Position) ([]protocol.CallHierarchyIncomingCall, error)

IncomingCalls returns an array of CallHierarchyIncomingCall for a file and the position within the file.

func InlayHint

func InlayHint(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pRng protocol.Range) ([]protocol.InlayHint, error)

func IsGenerated

func IsGenerated(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) bool

IsGenerated gets and reads the file denoted by uri and reports whether it contains a "generated file" comment as described at https://golang.org/s/generatedcode.

TODO(adonovan): opt: this function does too much. Move snapshot.ReadFile into the caller (most of which have already done it).

func NarrowestMetadataForFile

func NarrowestMetadataForFile(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (*metadata.Package, error)

NarrowestMetadataForFile returns metadata for the narrowest package (the one with the fewest files) that encloses the specified file. The result may be a test variant, but never an intermediate test variant.

func NarrowestPackageForFile

func NarrowestPackageForFile(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (*cache.Package, *parsego.File, error)

NarrowestPackageForFile is a convenience function that selects the narrowest non-ITV package to which this file belongs, type-checks it in the requested mode (full or workspace), and returns it, along with the parse tree of that file.

The "narrowest" package is the one with the fewest number of files that includes the given file. This solves the problem of test variants, as the test will have more files than the non-test package.

An intermediate test variant (ITV) package has identical source to a regular package but resolves imports differently. gopls should never need to type-check them.

Type-checking is expensive. Call snapshot.ParseGo if all you need is a parse tree, or snapshot.MetadataForFile if you only need metadata.

func NewBuiltinSignature

func NewBuiltinSignature(ctx context.Context, s *cache.Snapshot, name string) (*signature, error)

NewBuiltinSignature returns signature for the builtin object with a given name, if a builtin object with the name exists.

func NewSignature

func NewSignature(ctx context.Context, s *cache.Snapshot, pkg *cache.Package, sig *types.Signature, comment *ast.CommentGroup, qf types.Qualifier, mq MetadataQualifier) (*signature, error)

NewSignature returns formatted signature for a types.Signature struct.

func OutgoingCalls

OutgoingCalls returns an array of CallHierarchyOutgoingCall for a file and the position within the file.

func PackageDocHTML added in v0.16.0

func PackageDocHTML(viewID string, pkg *cache.Package, web Web) ([]byte, error)

PackageDocHTML formats the package documentation page.

The posURL function returns a URL that when visited, has the side effect of causing gopls to direct the client editor to navigate to the specified file/line/column position, in UTF-8 coordinates.

func PrepareCallHierarchy

func PrepareCallHierarchy(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pp protocol.Position) ([]protocol.CallHierarchyItem, error)

PrepareCallHierarchy returns an array of CallHierarchyItem for a file and the position within the file.

func References

func References(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pp protocol.Position, includeDeclaration bool) ([]protocol.Location, error)

References returns a list of all references (sorted with definitions before uses) to the object denoted by the identifier at the given file/position, searching the entire workspace.

func RemoveUnusedParameter

func RemoveUnusedParameter(ctx context.Context, fh file.Handle, rng protocol.Range, snapshot *cache.Snapshot) ([]protocol.DocumentChange, error)

RemoveUnusedParameter computes a refactoring to remove the parameter indicated by the given range, which must be contained within an unused parameter name or field.

This operation is a work in progress. Remaining TODO:

  • Handle function assignment correctly.
  • Improve the extra newlines in output.
  • Stream type checking via ForEachPackage.
  • Avoid unnecessary additional type checking.

func Rename

func Rename(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, pp protocol.Position, newName string) (map[protocol.DocumentURI][]protocol.TextEdit, bool, error)

Rename returns a map of TextEdits for each file modified when renaming a given identifier within a package and a boolean value of true for renaming package and false otherwise.

func SemanticTokens

func SemanticTokens(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng *protocol.Range) (*protocol.SemanticTokens, error)

func SignatureHelp

func SignatureHelp(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) (*protocol.SignatureInformation, int, error)

SignatureHelp returns information about the signature of the innermost function call enclosing the position, or nil if there is none. On success it also returns the parameter index of the position.

func TypeDefinition

func TypeDefinition(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) ([]protocol.Location, error)

TypeDefinition handles the textDocument/typeDefinition request for Go files.

func WidestPackageForFile

func WidestPackageForFile(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (*cache.Package, *parsego.File, error)

WidestPackageForFile is a convenience function that selects the widest non-ITV package to which this file belongs, type-checks it in the requested mode (full or workspace), and returns it, along with the parse tree of that file.

The "widest" package is the one with the most number of files that includes the given file. Which is the test variant if one exists.

An intermediate test variant (ITV) package has identical source to a regular package but resolves imports differently. gopls should never need to type-check them.

Type-checking is expensive. Call snapshot.ParseGo if all you need is a parse tree, or snapshot.MetadataForFile if you only need metadata.

func WorkspaceSymbols

func WorkspaceSymbols(ctx context.Context, matcher settings.SymbolMatcher, style settings.SymbolStyle, snapshots []*cache.Snapshot, query string) ([]protocol.SymbolInformation, error)

WorkspaceSymbols matches symbols across all views using the given query, according to the match semantics parameterized by matcherType and style.

The workspace symbol method is defined in the spec as follows:

The workspace symbol request is sent from the client to the server to
list project-wide symbols matching the query string.

It is unclear what "project-wide" means here, but given the parameters of workspace/symbol do not include any workspace identifier, then it has to be assumed that "project-wide" means "across all workspaces". Hence why WorkspaceSymbols receives the views []View.

However, it then becomes unclear what it would mean to call WorkspaceSymbols with a different configured SymbolMatcher per View. Therefore we assume that Session level configuration will define the SymbolMatcher to be used for the WorkspaceSymbols method.

Types

type FoldingRangeInfo

type FoldingRangeInfo struct {
	MappedRange protocol.MappedRange
	Kind        protocol.FoldingRangeKind
}

FoldingRangeInfo holds range and kind info of folding for an ast.Node

func FoldingRange

func FoldingRange(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, lineFoldingOnly bool) (ranges []*FoldingRangeInfo, err error)

FoldingRange gets all of the folding range for f.

type Hint

type Hint struct {
	Name string
	Doc  string
	Run  InlayHintFunc
}

type ImportPath

type ImportPath = metadata.ImportPath

type ImporterFunc

type ImporterFunc func(path string) (*types.Package, error)

An importFunc is an implementation of the single-method types.Importer interface based on a function value.

func (ImporterFunc) Import

func (f ImporterFunc) Import(path string) (*types.Package, error)

type InlayHintFunc

type InlayHintFunc func(node ast.Node, m *protocol.Mapper, tf *token.File, info *types.Info, q *types.Qualifier) []protocol.InlayHint

type MetadataQualifier

type MetadataQualifier func(PackageName, ImportPath, PackagePath) string

A MetadataQualifier is a function that qualifies an identifier declared in a package with the given package name, import path, and package path.

In scenarios where metadata is missing the provided PackageName and PackagePath may be empty, but ImportPath must always be non-empty.

func MetadataQualifierForFile

func MetadataQualifierForFile(s metadata.Source, f *ast.File, mp *metadata.Package) MetadataQualifier

MetadataQualifierForFile returns a metadata qualifier that chooses the best qualification of an imported package relative to the file f in package with metadata m.

type PackageID

type PackageID = metadata.PackageID

type PackageName

type PackageName = metadata.PackageName

type PackagePath

type PackagePath = metadata.PackagePath

func DocFragment added in v0.16.0

func DocFragment(pkg *cache.Package, pgf *parsego.File, start, end token.Pos) (pkgpath PackagePath, fragment, title string)

DocFragment finds the package and (optionally) symbol identified by the current selection, and returns the package path and the optional symbol URL fragment (e.g. "#Buffer.Len") for a symbol, along with a title for the code action.

It is called once to offer the code action, and again when the command is executed. This is slightly inefficient but ensures that the title and package/symbol logic are consistent in all cases.

It returns zeroes if there is nothing to see here (e.g. reference to a builtin).

func KnownPackagePaths

func KnownPackagePaths(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]PackagePath, error)

KnownPackagePaths returns a new list of package paths of all known packages in the package graph that could potentially be imported by the given file. The list is ordered lexicographically, except that all dot-free paths (standard packages) appear before dotful ones.

It is part of the gopls.list_known_packages command.

type PrepareItem

type PrepareItem struct {
	Range protocol.Range
	Text  string
}

A PrepareItem holds the result of a "prepare rename" operation: the source range and value of a selected identifier.

func PrepareRename

func PrepareRename(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, pp protocol.Position) (_ *PrepareItem, usererr, err error)

PrepareRename searches for a valid renaming at position pp.

The returned usererr is intended to be displayed to the user to explain why the prepare fails. Probably we could eliminate the redundancy in returning two errors, but for now this is done defensively.

type Web added in v0.16.0

type Web interface {
	// PkgURL forms URLs of package or symbol documentation.
	PkgURL(viewID string, path PackagePath, fragment string) protocol.URI

	// SrcURL forms URLs that cause the editor to open a file at a specific position.
	SrcURL(filename string, line, col8 int) protocol.URI
}

Web is an abstraction of gopls' web server.

Directories

Path Synopsis
Package completion provides core functionality for code completion in Go editors and tools.
Package completion provides core functionality for code completion in Go editors and tools.
snippet
Package snippet implements the specification for the LSP snippet format.
Package snippet implements the specification for the LSP snippet format.

Jump to

Keyboard shortcuts

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