gopls, internal/lsp: gofmt

Gofmt to update doc comments to the new formatting.

(There are so many files in x/tools I am breaking up the
gofmt'ing into multiple CLs.)

For golang/go#51082.

Change-Id: Ife11502fe1e59a04d53dba9edccd3043e57f9ae8
Reviewed-on: https://go-review.googlesource.com/c/tools/+/399358
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Auto-Submit: Russ Cox <rsc@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Russ Cox 2022-04-11 22:38:20 -04:00 committed by Gopher Robot
parent 5fef6fdaed
commit 2bbdb7a52e
26 changed files with 157 additions and 145 deletions

View File

@ -144,9 +144,9 @@ var (
// is the path to a workspace root, and -didchange_file is the
// workspace-relative path to a file to modify. e.g.:
//
// go test -run=TestBenchmarkDidChange \
// -didchange_dir=path/to/kubernetes \
// -didchange_file=pkg/util/hash/hash.go
// go test -run=TestBenchmarkDidChange \
// -didchange_dir=path/to/kubernetes \
// -didchange_file=pkg/util/hash/hash.go
func TestBenchmarkDidChange(t *testing.T) {
if *benchDir == "" {
t.Skip("-didchange_dir is not set")

View File

@ -91,10 +91,11 @@ func endPosInBuffer(env *Env, name string) fake.Pos {
// Benchmark completion at a specified file and location. When no CLI options
// are specified, this test is skipped.
// To Run (from x/tools/gopls) against the dummy function above:
// go test -v ./internal/regtest/bench -run=TestBenchmarkConfiguredCompletion
// -completion_workdir="$HOME/Developer/tools"
// -completion_file="gopls/internal/regtest/completion_bench_test.go"
// -completion_regexp="dummyCompletionFunction.*fmt\.Printf\(\"%s\", s(\))"
//
// go test -v ./internal/regtest/bench -run=TestBenchmarkConfiguredCompletion
// -completion_workdir="$HOME/Developer/tools"
// -completion_file="gopls/internal/regtest/completion_bench_test.go"
// -completion_regexp="dummyCompletionFunction.*fmt\.Printf\(\"%s\", s(\))"
func TestBenchmarkConfiguredCompletion(t *testing.T) {
benchmarkCompletion(completionOptions, t)
}

View File

@ -220,8 +220,9 @@ func Vuln() {
`
// testClient contains the following test vulnerabilities
// golang.org/amod/avuln.{VulnData.Vuln1, vulnData.Vuln2}
// golang.org/bmod/bvuln.{Vuln}
//
// golang.org/amod/avuln.{VulnData.Vuln1, vulnData.Vuln2}
// golang.org/bmod/bvuln.{Vuln}
var testClient1 = &mockClient{
ret: map[string][]*osv.Entry{
"golang.org/amod": {

View File

@ -369,8 +369,7 @@ func spanToRange(pkg *pkg, spn span.Span) (protocol.Range, error) {
// It works only on errors whose message is prefixed by colon,
// followed by a space (": "). For example:
//
// attributes.go:13:1: expected 'package', found 'type'
//
// attributes.go:13:1: expected 'package', found 'type'
func parseGoListError(input, wd string) span.Span {
input = strings.TrimSpace(input)
msgIndex := strings.Index(input, ": ")

View File

@ -359,9 +359,9 @@ var moduleVersionInErrorRe = regexp.MustCompile(`[:\s]([+-._~0-9A-Za-z]+)@([+-._
// matchErrorToModule matches a go command error message to a go.mod file.
// Some examples:
//
// example.com@v1.2.2: reading example.com/@v/v1.2.2.mod: no such file or directory
// go: github.com/cockroachdb/apd/v2@v2.0.72: reading github.com/cockroachdb/apd/go.mod at revision v2.0.72: unknown revision v2.0.72
// go: example.com@v1.2.3 requires\n\trandom.org@v1.2.3: parsing go.mod:\n\tmodule declares its path as: bob.org\n\tbut was required as: random.org
// example.com@v1.2.2: reading example.com/@v/v1.2.2.mod: no such file or directory
// go: github.com/cockroachdb/apd/v2@v2.0.72: reading github.com/cockroachdb/apd/go.mod at revision v2.0.72: unknown revision v2.0.72
// go: example.com@v1.2.3 requires\n\trandom.org@v1.2.3: parsing go.mod:\n\tmodule declares its path as: bob.org\n\tbut was required as: random.org
//
// It returns the location of a reference to the one of the modules and true
// if one exists. If none is found it returns a fallback location and false.

View File

@ -778,11 +778,11 @@ func fixSrc(f *ast.File, tok *token.File, src []byte) (newSrc []byte) {
// fixMissingCurlies adds in curly braces for block statements that
// are missing curly braces. For example:
//
// if foo
// if foo
//
// becomes
//
// if foo {}
// if foo {}
func fixMissingCurlies(f *ast.File, b *ast.BlockStmt, parent ast.Node, tok *token.File, src []byte) []byte {
// If the "{" is already in the source code, there isn't anything to
// fix since we aren't missing curlies.
@ -875,23 +875,22 @@ func fixMissingCurlies(f *ast.File, b *ast.BlockStmt, parent ast.Node, tok *toke
// "case" and "default" keywords as inside the switch statement. For
// example:
//
// switch {
// def<>
// }
// switch {
// def<>
// }
//
// gets parsed like:
//
// switch {
// }
// switch {
// }
//
// Later we manually pull out the "def" token, but we need to detect
// that our "<>" position is inside the switch block. To do that we
// move the curly brace so it looks like:
//
// switch {
//
// }
// switch {
//
// }
func fixEmptySwitch(body *ast.BlockStmt, tok *token.File, src []byte) {
// We only care about empty switch statements.
if len(body.List) > 0 || !body.Rbrace.IsValid() {
@ -921,9 +920,10 @@ func fixEmptySwitch(body *ast.BlockStmt, tok *token.File, src []byte) {
// fixDanglingSelector inserts real "_" selector expressions in place
// of phantom "_" selectors. For example:
//
// func _() {
// x.<>
// }
// func _() {
// x.<>
// }
//
// var x struct { i int }
//
// To fix completion at "<>", we insert a real "_" after the "." so the

View File

@ -557,9 +557,11 @@ func (s *snapshot) IgnoredFile(uri span.URI) bool {
return false
}
// checkIgnored implements go list's exclusion rules. go help list:
// Directory and file names that begin with "." or "_" are ignored
// by the go tool, as are directories named "testdata".
// checkIgnored implements go list's exclusion rules.
// Quoting “go help list”:
//
// Directory and file names that begin with "." or "_" are ignored
// by the go tool, as are directories named "testdata".
func checkIgnored(suffix string) bool {
for _, component := range strings.Split(suffix, string(filepath.Separator)) {
if len(component) == 0 {
@ -796,6 +798,7 @@ func go111moduleForVersion(go111module string, goversion int) go111module {
// - Then, a parent directory containing a go.mod file.
// - Then, a child directory containing a go.mod file, if there is exactly
// one (non-experimental only).
//
// Otherwise, it returns folder.
// TODO (rFindley): move this to workspace.go
// TODO (rFindley): simplify this once workspace modules are enabled by default.

View File

@ -50,10 +50,10 @@ func (s workspaceSource) String() string {
// gopls.mod file, to provide support for multi-module workspaces.
//
// Specifically, it provides:
// - the set of modules contained within in the workspace root considered to
// be 'active'
// - the workspace modfile, to be used for the go command `-modfile` flag
// - the set of workspace directories
// - the set of modules contained within in the workspace root considered to
// be 'active'
// - the workspace modfile, to be used for the go command `-modfile` flag
// - the set of workspace directories
//
// This type is immutable (or rather, idempotent), so that it may be shared
// across multiple snapshots.

View File

@ -214,8 +214,9 @@ func lspName(methodName string) string {
// Initialisms are grouped as a single word.
//
// For example:
// "RunTests" -> []string{"Run", "Tests"}
// "GCDetails" -> []string{"GC", "Details"}
//
// "RunTests" -> []string{"Run", "Tests"}
// "GCDetails" -> []string{"GC", "Details"}
func splitCamel(s string) []string {
var words []string
for len(s) > 0 {

View File

@ -25,8 +25,7 @@ func (c Command) ID() string {
//
// Example usage:
//
// jsonArgs, err := MarshalArgs(1, "hello", true, StructuredArg{42, 12.6})
//
// jsonArgs, err := MarshalArgs(1, "hello", true, StructuredArg{42, 12.6})
func MarshalArgs(args ...interface{}) ([]json.RawMessage, error) {
var out []json.RawMessage
for _, arg := range args {
@ -44,14 +43,13 @@ func MarshalArgs(args ...interface{}) ([]json.RawMessage, error) {
//
// Example usage:
//
// var (
// num int
// str string
// bul bool
// structured StructuredArg
// )
// err := UnmarshalArgs(args, &num, &str, &bul, &structured)
//
// var (
// num int
// str string
// bul bool
// structured StructuredArg
// )
// err := UnmarshalArgs(args, &num, &str, &bul, &structured)
func UnmarshalArgs(jsonArgs []json.RawMessage, args ...interface{}) error {
if len(args) != len(jsonArgs) {
return fmt.Errorf("DecodeArgs: expected %d input arguments, got %d JSON arguments", len(args), len(jsonArgs))

View File

@ -145,7 +145,8 @@ func NewEditor(sandbox *Sandbox, config EditorConfig) *Editor {
// editor.
//
// It returns the editor, so that it may be called as follows:
// editor, err := NewEditor(s).Connect(ctx, conn)
//
// editor, err := NewEditor(s).Connect(ctx, conn)
func (e *Editor) Connect(ctx context.Context, conn jsonrpc2.Conn, hooks ClientHooks) (*Editor, error) {
e.serverConn = conn
e.Server = protocol.ServerDispatcher(conn)
@ -633,6 +634,7 @@ func (e *Editor) RegexpRange(bufName, re string) (Pos, Pos, error) {
// bufName. For convenience, RegexpSearch supports the following two modes:
// 1. If re has no subgroups, return the position of the match for re itself.
// 2. If re has one subgroup, return the position of the first subgroup.
//
// It returns an error re is invalid, has more than one subgroup, or doesn't
// match the buffer.
func (e *Editor) RegexpSearch(bufName, re string) (Pos, error) {

View File

@ -178,7 +178,8 @@ func validateConfig(config SandboxConfig) error {
// splitModuleVersionPath extracts module information from files stored in the
// directory structure modulePath@version/suffix.
// For example:
// splitModuleVersionPath("mod.com@v1.2.3/package") = ("mod.com", "v1.2.3", "package")
//
// splitModuleVersionPath("mod.com@v1.2.3/package") = ("mod.com", "v1.2.3", "package")
func splitModuleVersionPath(path string) (modulePath, version, suffix string) {
parts := strings.Split(path, "/")
var modulePathParts []string

View File

@ -5,7 +5,6 @@
// Benchmark results:
//
// BenchmarkMatcher-12 1000000 1615 ns/op 30.95 MB/s 0 B/op 0 allocs/op
//
package fuzzy_test
import (

View File

@ -10,21 +10,22 @@ import (
// SymbolMatcher implements a fuzzy matching algorithm optimized for Go symbols
// of the form:
// example.com/path/to/package.object.field
//
// example.com/path/to/package.object.field
//
// Knowing that we are matching symbols like this allows us to make the
// following optimizations:
// - We can incorporate right-to-left relevance directly into the score
// calculation.
// - We can match from right to left, discarding leading bytes if the input is
// too long.
// - We just take the right-most match without losing too much precision. This
// allows us to use an O(n) algorithm.
// - We can operate directly on chunked strings; in many cases we will
// be storing the package path and/or package name separately from the
// symbol or identifiers, so doing this avoids allocating strings.
// - We can return the index of the right-most match, allowing us to trim
// irrelevant qualification.
// - We can incorporate right-to-left relevance directly into the score
// calculation.
// - We can match from right to left, discarding leading bytes if the input is
// too long.
// - We just take the right-most match without losing too much precision. This
// allows us to use an O(n) algorithm.
// - We can operate directly on chunked strings; in many cases we will
// be storing the package path and/or package name separately from the
// symbol or identifiers, so doing this avoids allocating strings.
// - We can return the index of the right-most match, allowing us to trim
// irrelevant qualification.
//
// This implementation is experimental, serving as a reference fast algorithm
// to compare to the fuzzy algorithm implemented by Matcher.

View File

@ -6,11 +6,11 @@
//
// See https://microsoft.github.io/language-server-protocol/specification#textDocuments
// for a description of LSP positions. Notably:
// - Positions are specified by a 0-based line count and 0-based utf-16
// character offset.
// - Positions are line-ending agnostic: there is no way to specify \r|\n or
// \n|. Instead the former maps to the end of the current line, and the
// latter to the start of the next line.
// - Positions are specified by a 0-based line count and 0-based utf-16
// character offset.
// - Positions are line-ending agnostic: there is no way to specify \r|\n or
// \n|. Instead the former maps to the end of the current line, and the
// latter to the start of the next line.
package lsppos
import (

View File

@ -49,20 +49,20 @@ func (tracker *Tracker) SetSupportsWorkDoneProgress(b bool) {
// non-nil. In this case, cancel is called when the work done
//
// Example:
// func Generate(ctx) (err error) {
// ctx, cancel := context.WithCancel(ctx)
// defer cancel()
// work := s.progress.start(ctx, "generate", "running go generate", cancel)
// defer func() {
// if err != nil {
// work.end(ctx, fmt.Sprintf("generate failed: %v", err))
// } else {
// work.end(ctx, "done")
// }
// }()
// // Do the work...
// }
//
// func Generate(ctx) (err error) {
// ctx, cancel := context.WithCancel(ctx)
// defer cancel()
// work := s.progress.start(ctx, "generate", "running go generate", cancel)
// defer func() {
// if err != nil {
// work.end(ctx, fmt.Sprintf("generate failed: %v", err))
// } else {
// work.end(ctx, "done")
// }
// }()
// // Do the work...
// }
func (t *Tracker) Start(ctx context.Context, title, message string, token protocol.ProgressToken, cancel func()) *WorkDone {
wd := &WorkDone{
ctx: xcontext.Detach(ctx),

View File

@ -14,13 +14,13 @@
// user interactions in ordinary Go tests, validate them, and run them in a
// variety of execution modes (see gopls/doc/daemon.md for more information on
// execution modes). This is achieved roughly as follows:
// + the Runner type starts and connects to a gopls instance for each
// configured execution mode.
// + the Env type provides a collection of resources to use in writing tests
// (for example a temporary working directory and fake text editor)
// + user interactions with these resources are scripted using test wrappers
// around the API provided by the golang.org/x/tools/internal/lsp/fake
// package.
// - the Runner type starts and connects to a gopls instance for each
// configured execution mode.
// - the Env type provides a collection of resources to use in writing tests
// (for example a temporary working directory and fake text editor)
// - user interactions with these resources are scripted using test wrappers
// around the API provided by the golang.org/x/tools/internal/lsp/fake
// package.
//
// Regressions are expressed in terms of Expectations, which at a high level
// are conditions that we expect to be met (or not to be met) at some point

View File

@ -91,7 +91,7 @@ var (
)
// commentEscape escapes comment text for markdown. If nice is set,
// also turn `` into “; and '' into ”;.
// also turn double ` and ' into “ and ”.
func commentEscape(w io.Writer, text string, nice bool) {
if nice {
text = convertQuotes(text)

View File

@ -24,19 +24,17 @@ func (c *completer) addStatementCandidates() {
// addAssignAppend offers a completion candidate of the form:
//
// someSlice = append(someSlice, )
// someSlice = append(someSlice, )
//
// It will offer the "append" completion in two situations:
// It will offer the "append" completion in either of two situations:
//
// 1. Position is in RHS of assign, prefix matches "append", and
// corresponding LHS object is a slice. For example,
// "foo = ap<>" completes to "foo = append(foo, )".
// 1. Position is in RHS of assign, prefix matches "append", and
// corresponding LHS object is a slice. For example,
// "foo = ap<>" completes to "foo = append(foo, )".
//
// Or
//
// 2. Prefix is an ident or selector in an *ast.ExprStmt (i.e.
// beginning of statement), and our best matching candidate is a
// slice. For example: "foo.ba" completes to "foo.bar = append(foo.bar, )".
// 2. Prefix is an ident or selector in an *ast.ExprStmt (i.e.
// beginning of statement), and our best matching candidate is a
// slice. For example: "foo.ba" completes to "foo.bar = append(foo.bar, )".
func (c *completer) addAssignAppend() {
if len(c.path) < 3 {
return
@ -164,15 +162,15 @@ func (c *completer) topCandidate() *CompletionItem {
// addErrCheck offers a completion candidate of the form:
//
// if err != nil {
// return nil, err
// }
// if err != nil {
// return nil, err
// }
//
// In the case of test functions, it offers a completion candidate of the form:
//
// if err != nil {
// t.Fatal(err)
// }
// if err != nil {
// t.Fatal(err)
// }
//
// The position must be in a function that returns an error, and the
// statement preceding the position must be an assignment where the

View File

@ -259,8 +259,8 @@ func fieldsAccessible(s *types.Struct, p *types.Package) bool {
// prevStmt returns the statement that precedes the statement containing pos.
// For example:
//
// foo := 1
// bar(1 + 2<>)
// foo := 1
// bar(1 + 2<>)
//
// If "<>" is pos, prevStmt returns "foo := 1"
func prevStmt(pos token.Pos, path []ast.Node) ast.Stmt {

View File

@ -178,7 +178,6 @@ func (r *renamer) checkInLocalScope(from types.Object) {
//
// Removing the old name (and all references to it) is always safe, and
// requires no checks.
//
func (r *renamer) checkInLexicalScope(from types.Object, pkg Package) {
b := from.Parent() // the block defining the 'from' object
if b != nil {
@ -533,10 +532,11 @@ func (r *renamer) selectionConflict(from types.Object, delta int, syntax *ast.Se
// - declaration conflicts
// - selection ambiguity/changes
// - entailed renamings of assignable concrete/interface types.
// We reject renamings initiated at concrete methods if it would
// change the assignability relation. For renamings of abstract
// methods, we rename all methods transitively coupled to it via
// assignability.
//
// We reject renamings initiated at concrete methods if it would
// change the assignability relation. For renamings of abstract
// methods, we rename all methods transitively coupled to it via
// assignability.
func (r *renamer) checkMethod(from *types.Func) {
// e.g. error.Error
if from.Pkg() == nil {
@ -827,7 +827,6 @@ func someUse(info *types.Info, obj types.Object) *ast.Ident {
// exact is defined as for astutil.PathEnclosingInterval.
//
// The zero value is returned if not found.
//
func pathEnclosingInterval(fset *token.FileSet, pkg Package, start, end token.Pos) (resPkg Package, path []ast.Node, exact bool) {
pkgs := []Package{pkg}
for _, f := range pkg.GetSyntax() {

View File

@ -179,10 +179,11 @@ type methodData struct {
}
// printStubMethod takes methodData and returns Go code that represents the given method such as:
// // {{ .Method }} implements {{ .Interface }}
// func ({{ .Concrete }}) {{ .Method }}{{ .Signature }} {
// panic("unimplemented")
// }
//
// // {{ .Method }} implements {{ .Interface }}
// func ({{ .Concrete }}) {{ .Method }}{{ .Signature }} {
// panic("unimplemented")
// }
func printStubMethod(md methodData) []byte {
var b bytes.Buffer
fmt.Fprintf(&b, "// %s implements %s\n", md.Method, md.Interface)
@ -229,22 +230,25 @@ func getStubNodes(pgf *ParsedGoFile, pRng protocol.Range) ([]ast.Node, token.Pos
missingMethods takes a concrete type and returns any missing methods for the given interface as well as
any missing interface that might have been embedded to its parent. For example:
type I interface {
io.Writer
Hello()
}
returns []*missingInterface{
{
iface: *types.Interface (io.Writer),
file: *ast.File: io.go,
missing []*types.Func{Write},
},
{
iface: *types.Interface (I),
file: *ast.File: myfile.go,
missing: []*types.Func{Hello}
},
}
type I interface {
io.Writer
Hello()
}
returns
[]*missingInterface{
{
iface: *types.Interface (io.Writer),
file: *ast.File: io.go,
missing []*types.Func{Write},
},
{
iface: *types.Interface (I),
file: *ast.File: myfile.go,
missing: []*types.Func{Hello}
},
}
*/
func missingMethods(ctx context.Context, snapshot Snapshot, concMS *types.MethodSet, concPkg *types.Package, ifaceObj types.Object, ifacePkg Package, visited map[string]struct{}) ([]*missingInterface, error) {
iface, ok := ifaceObj.Type().Underlying().(*types.Interface)

View File

@ -343,9 +343,11 @@ func qualifyExpr(expr ast.Expr, srcpkg, pkg Package, clonedInfo map[token.Pos]*t
// cloneExpr only clones expressions that appear in the parameters or return
// values of a function declaration. The original expression may be returned
// to the caller in 2 cases:
// (1) The expression has no pointer fields.
// (2) The expression cannot appear in an *ast.FuncType, making it
// unnecessary to clone.
//
// 1. The expression has no pointer fields.
// 2. The expression cannot appear in an *ast.FuncType, making it
// unnecessary to clone.
//
// This function also keeps track of selector expressions in which the X is a
// package name and marks them in a map along with their type information, so
// that this information can be used when rewriting the expression.

View File

@ -159,6 +159,7 @@ func posToMappedRange(snapshot Snapshot, pkg Package, pos, end token.Pos) (Mappe
}
// Matches cgo generated comment as well as the proposed standard:
//
// https://golang.org/s/generatedcode
var generatedRx = regexp.MustCompile(`// .*DO NOT EDIT\.?`)

View File

@ -38,8 +38,8 @@ const maxSymbols = 100
//
// 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.
// 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
@ -140,11 +140,11 @@ func packageSymbolMatch(name string, pkg Metadata, matcher matcherFunc) ([]strin
// match a given query.
//
// How we match symbols is parameterized by two interfaces:
// * A matcherFunc determines how well a string symbol matches a query. It
// returns a non-negative score indicating the quality of the match. A score
// of zero indicates no match.
// * A symbolizer determines how we extract the symbol for an object. This
// enables the 'symbolStyle' configuration option.
// - A matcherFunc determines how well a string symbol matches a query. It
// returns a non-negative score indicating the quality of the match. A score
// of zero indicates no match.
// - A symbolizer determines how we extract the symbol for an object. This
// enables the 'symbolStyle' configuration option.
type symbolCollector struct {
// These types parameterize the symbol-matching pass.
matchers []matcherFunc
@ -213,9 +213,10 @@ func newFuzzyMatcher(query string) matcherFunc {
// of all field queries.
//
// Special characters:
// ^ match exact prefix
// $ match exact suffix
// ' match exact
//
// ^ match exact prefix
// $ match exact suffix
// ' match exact
//
// In all three of these special queries, matches are 'smart-cased', meaning
// they are case sensitive if the symbol query contains any upper-case

View File

@ -154,7 +154,8 @@ func parseBuffer(buf []byte) *Parsed {
// FindLiteralBefore locates the first preceding string literal
// returning its position and length in buf
// or returns -1 if there is none. Assume "", rather than ``, for now
// or returns -1 if there is none.
// Assume double-quoted string rather than backquoted string for now.
func (p *Parsed) FindLiteralBefore(pos int) (int, int) {
left, right := -1, -1
for i := pos - 1; i >= 0; i-- {