golang

package
v0.15.3 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: BSD-3-Clause Imports: 76 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"
)
View Source
const (
	ParseHeader = parsego.ParseHeader
	ParseFull   = parsego.ParseFull
)

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,
	},
}
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.

func ApplyFix

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

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

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 CanExtractFunction

func CanExtractFunction(tok *token.File, start, end token.Pos, src []byte, file *ast.File) (*fnExtractParams, bool, bool, error)

CanExtractFunction reports whether the code in the given range can be extracted to a function.

func CanExtractVariable

func CanExtractVariable(start, end token.Pos, file *ast.File) (ast.Expr, []ast.Node, bool, error)

CanExtractVariable reports whether the code in the given range can be extracted to a variable.

func CanInvertIfCondition

func CanInvertIfCondition(file *ast.File, start, end token.Pos) (*ast.IfStmt, bool, error)

CanInvertIfCondition reports whether we can do invert-if-condition on the code in the given range

func CodeActions

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

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

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 *ParsedGoFile, fix *imports.ImportFix) ([]protocol.TextEdit, error)

ComputeOneImportFixEdits returns text edits for a single import fix.

func ConvertStringLiteral

func ConvertStringLiteral(pgf *ParsedGoFile, fh file.Handle, rng protocol.Range) (protocol.CodeAction, bool)

ConvertStringLiteral reports whether we can convert between raw and interpreted string literals in the [start, end), along with a CodeAction containing the edits.

Only the following conditions are true, the action in result is valid

  • [start, end) is enclosed by a string literal
  • if the string is interpreted string, need check whether the convert is allowed

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 Deref

func Deref(typ types.Type) types.Type

Deref returns a pointer's element type, traversing as many levels as needed. Otherwise it returns typ.

It can return a pointer type for cyclic types (see golang/go#45510).

func DocumentSymbols

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

func EmbedDefinition

func EmbedDefinition(m *protocol.Mapper, pos protocol.Position) ([]protocol.Location, error)

EmbedDefinition finds a file matching the embed directive at pos in the mapped file. If there is no embed directive at pos, returns ErrNoEmbed. If multiple files match the embed pattern, one is picked at random.

func EnclosingStaticCall

func EnclosingStaticCall(pkg *cache.Package, pgf *ParsedGoFile, start, end token.Pos) (*ast.CallExpr, *types.Func, error)

EnclosingStaticCall returns the innermost function call enclosing the selected range, along with the callee.

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 FormatNodeFile

func FormatNodeFile(file *token.File, n ast.Node) string

FormatNodeFile is like FormatNode, but requires only the token.File for the syntax containing the given 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 GCOptimizationDetails

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

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) (*protocol.Hover, error)

Hover implements the "textDocument/hover" RPC for Go files.

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 LensFuncs

func LensFuncs() map[command.Command]LensFunc

LensFuncs returns the supported lensFuncs for Go files.

func LinknameDefinition

func LinknameDefinition(ctx context.Context, snapshot *cache.Snapshot, m *protocol.Mapper, from protocol.Position) ([]protocol.Location, error)

LinknameDefinition finds the definition of the linkname directive in m at pos. If there is no linkname directive at pos, returns ErrNoLinkname.

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 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 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.DocumentChanges, 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)

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 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 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 ParamInfo

type ParamInfo struct {
	Decl       *ast.FuncDecl // enclosing func decl (non-nil)
	FieldIndex int           // index of Field in Decl.Type.Params, or -1
	Field      *ast.Field    // enclosing field of Decl, or nil if range not among parameters
	NameIndex  int           // index of Name in Field.Names, or nil
	Name       *ast.Ident    // indicated name (either enclosing, or Field.Names[0] if len(Field.Names) == 1)
}

ParamInfo records information about a param identified by a position.

func FindParam

func FindParam(pgf *ParsedGoFile, rng protocol.Range) (*ParamInfo, error)

FindParam finds the parameter information spanned by the given range.

type ParsedGoFile

type ParsedGoFile = parsego.File

func NarrowestPackageForFile

func NarrowestPackageForFile(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (*cache.Package, *ParsedGoFile, 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 WidestPackageForFile

func WidestPackageForFile(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (*cache.Package, *ParsedGoFile, 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.

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 TestFn

type TestFn struct {
	Name string
	Rng  protocol.Range
}

type TestFns

type TestFns struct {
	Tests      []TestFn
	Benchmarks []TestFn
}

func TestsAndBenchmarks

func TestsAndBenchmarks(pkg *cache.Package, pgf *ParsedGoFile) (TestFns, error)

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