text
stringlengths 2
1.1M
| id
stringlengths 11
117
| metadata
dict | __index_level_0__
int64 0
885
|
---|---|---|---|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// go:build ignore
package testdata
type I interface {
Foo()
}
type J interface {
I
Bar()
}
type A struct{}
func (a A) Foo() {}
func (a A) Bar() {}
type B struct {
a A
i I
}
func Do() B {
b := B{}
return b
}
func Baz(b B) {
var j J
j = b.a
j.Bar()
b.i = j
Do().i.Foo()
}
// Relevant SSA:
// func Baz(b B):
// t0 = local B (b)
// *t0 = b
// t1 = &t0.a [#0] // no flow here since a is of concrete type
// t2 = *t1
// t3 = make J <- A (t2)
// t4 = invoke t3.Bar()
// t5 = &t0.i [#1]
// t6 = change interface I <- J (t3)
// *t5 = t6
// t7 = Do()
// t8 = t7.i [#0]
// t9 = (A).Foo(t8)
// return
// WANT:
// Field(testdata.B:i) -> Local(t5), Local(t8)
// Local(t5) -> Field(testdata.B:i)
// Local(t2) -> Local(t3)
// Local(t3) -> Local(t6)
// Local(t6) -> Local(t5)
| tools/go/callgraph/vta/testdata/src/fields.go/0 | {
"file_path": "tools/go/callgraph/vta/testdata/src/fields.go",
"repo_id": "tools",
"token_count": 464
} | 700 |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// go:build ignore
package testdata
type A struct{}
func (a A) foo() {}
type I interface{ foo() }
func Baz(i I) {
j := &i
k := &j
**k = A{}
i.foo()
(**k).foo()
}
// Relevant SSA:
// func Baz(i I):
// t0 = new I (i)
// *t0 = i
// t1 = new *I (j)
// *t1 = t0
// t2 = *t1
// t3 = make I <- A (struct{}{}:A) I
// *t2 = t3
// t4 = *t0
// t5 = invoke t4.foo()
// t6 = *t1
// t7 = *t6
// t8 = invoke t7.foo()
// Flow chain showing that A reaches i.foo():
// Constant(A) -> t3 -> t2 <-> PtrInterface(I) <-> t0 -> t4
// Flow chain showing that A reaches (**k).foo():
// Constant(A) -> t3 -> t2 <-> PtrInterface(I) <-> t6 -> t7
// WANT:
// Local(i) -> Local(t0)
// Local(t0) -> Local(t4), PtrInterface(testdata.I)
// PtrInterface(testdata.I) -> Local(t0), Local(t2), Local(t6)
// Local(t2) -> PtrInterface(testdata.I)
// Constant(testdata.A) -> Local(t3)
// Local(t3) -> Local(t2)
// Local(t6) -> Local(t7), PtrInterface(testdata.I)
| tools/go/callgraph/vta/testdata/src/store_load_alias.go/0 | {
"file_path": "tools/go/callgraph/vta/testdata/src/store_load_alias.go",
"repo_id": "tools",
"token_count": 533
} | 701 |
// This file is named go.fake.mod so it does not define a real module, which
// would make the contents of this directory unavailable to the test when run
// from outside the repository.
go 1.23.0 //@mark(αMarker, "1.23.0")
use ./αβ //@mark(βMarker, "αβ")
| tools/go/expect/testdata/go.fake.work/0 | {
"file_path": "tools/go/expect/testdata/go.fake.work",
"repo_id": "tools",
"token_count": 84
} | 702 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Except for this comment, this file is a verbatim copy of the file
// with the same name in $GOROOT/src/go/internal/gccgoimporter.
package gccgoimporter
import (
"go/types"
"runtime"
"testing"
)
// importablePackages is a list of packages that we verify that we can
// import. This should be all standard library packages in all relevant
// versions of gccgo. Note that since gccgo follows a different release
// cycle, and since different systems have different versions installed,
// we can't use the last-two-versions rule of the gc toolchain.
var importablePackages = [...]string{
"archive/tar",
"archive/zip",
"bufio",
"bytes",
"compress/bzip2",
"compress/flate",
"compress/gzip",
"compress/lzw",
"compress/zlib",
"container/heap",
"container/list",
"container/ring",
"crypto/aes",
"crypto/cipher",
"crypto/des",
"crypto/dsa",
"crypto/ecdsa",
"crypto/elliptic",
"crypto",
"crypto/hmac",
"crypto/md5",
"crypto/rand",
"crypto/rc4",
"crypto/rsa",
"crypto/sha1",
"crypto/sha256",
"crypto/sha512",
"crypto/subtle",
"crypto/tls",
"crypto/x509",
"crypto/x509/pkix",
"database/sql/driver",
"database/sql",
"debug/dwarf",
"debug/elf",
"debug/gosym",
"debug/macho",
"debug/pe",
"encoding/ascii85",
"encoding/asn1",
"encoding/base32",
"encoding/base64",
"encoding/binary",
"encoding/csv",
"encoding/gob",
// "encoding", // Added in GCC 4.9.
"encoding/hex",
"encoding/json",
"encoding/pem",
"encoding/xml",
"errors",
"expvar",
"flag",
"fmt",
"go/ast",
"go/build",
"go/doc",
// "go/format", // Added in GCC 4.8.
"go/parser",
"go/printer",
"go/scanner",
"go/token",
"hash/adler32",
"hash/crc32",
"hash/crc64",
"hash/fnv",
"hash",
"html",
"html/template",
"image/color",
// "image/color/palette", // Added in GCC 4.9.
"image/draw",
"image/gif",
"image",
"image/jpeg",
"image/png",
"index/suffixarray",
"io",
"io/ioutil",
"log",
"log/syslog",
"math/big",
"math/cmplx",
"math",
"math/rand",
"mime",
"mime/multipart",
"net",
"net/http/cgi",
// "net/http/cookiejar", // Added in GCC 4.8.
"net/http/fcgi",
"net/http",
"net/http/httptest",
"net/http/httputil",
"net/http/pprof",
"net/mail",
"net/rpc",
"net/rpc/jsonrpc",
"net/smtp",
"net/textproto",
"net/url",
"os/exec",
"os",
"os/signal",
"os/user",
"path/filepath",
"path",
"reflect",
"regexp",
"regexp/syntax",
"runtime/debug",
"runtime",
"runtime/pprof",
"sort",
"strconv",
"strings",
"sync/atomic",
"sync",
"syscall",
"testing",
"testing/iotest",
"testing/quick",
"text/scanner",
"text/tabwriter",
"text/template",
"text/template/parse",
"time",
"unicode",
"unicode/utf16",
"unicode/utf8",
}
func TestInstallationImporter(t *testing.T) {
// This test relies on gccgo being around.
gpath := gccgoPath()
if gpath == "" {
t.Skip("This test needs gccgo")
}
if runtime.GOOS == "aix" {
// We don't yet have a debug/xcoff package for reading
// object files on AIX. Remove this skip if/when issue #29038
// is implemented (see also issue #49445).
t.Skip("no support yet for debug/xcoff")
}
var inst GccgoInstallation
err := inst.InitFromDriver(gpath)
if err != nil {
t.Fatal(err)
}
imp := inst.GetImporter(nil, nil)
// Ensure we don't regress the number of packages we can parse. First import
// all packages into the same map and then each individually.
pkgMap := make(map[string]*types.Package)
for _, pkg := range importablePackages {
_, err = imp(pkgMap, pkg, ".", nil)
if err != nil {
t.Error(err)
}
}
for _, pkg := range importablePackages {
_, err = imp(make(map[string]*types.Package), pkg, ".", nil)
if err != nil {
t.Error(err)
}
}
// Test for certain specific entities in the imported data.
for _, test := range [...]importerTest{
{pkgpath: "io", name: "Reader", want: "type Reader interface{Read(p []byte) (n int, err error)}"},
{pkgpath: "io", name: "ReadWriter", want: "type ReadWriter interface{Reader; Writer}"},
{pkgpath: "math", name: "Pi", want: "const Pi untyped float"},
{pkgpath: "math", name: "Sin", want: "func Sin(x float64) float64"},
{pkgpath: "sort", name: "Search", want: "func Search(n int, f func(int) bool) int"},
{pkgpath: "unsafe", name: "Pointer", want: "type Pointer"},
} {
runImporterTest(t, imp, nil, &test)
}
}
| tools/go/internal/gccgoimporter/gccgoinstallation_test.go/0 | {
"file_path": "tools/go/internal/gccgoimporter/gccgoinstallation_test.go",
"repo_id": "tools",
"token_count": 1852
} | 703 |
v1;
package imports;
pkgpath imports;
priority 7;
import fmt fmt "fmt";
init imports imports..import 7 math math..import 1 runtime runtime..import 1 strconv strconv..import 2 io io..import 3 reflect reflect..import 3 syscall syscall..import 3 time time..import 4 os os..import 5 fmt fmt..import 6;
var Hello <type -16>;
| tools/go/internal/gccgoimporter/testdata/imports.gox/0 | {
"file_path": "tools/go/internal/gccgoimporter/testdata/imports.gox",
"repo_id": "tools",
"token_count": 93
} | 704 |
package pointer
type Int8Ptr *int8
| tools/go/internal/gccgoimporter/testdata/pointer.go/0 | {
"file_path": "tools/go/internal/gccgoimporter/testdata/pointer.go",
"repo_id": "tools",
"token_count": 12
} | 705 |
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package packages loads Go packages for inspection and analysis.
The [Load] function takes as input a list of patterns and returns a
list of [Package] values describing individual packages matched by those
patterns.
A [Config] specifies configuration options, the most important of which is
the [LoadMode], which controls the amount of detail in the loaded packages.
Load passes most patterns directly to the underlying build tool.
The default build tool is the go command.
Its supported patterns are described at
https://pkg.go.dev/cmd/go#hdr-Package_lists_and_patterns.
Other build systems may be supported by providing a "driver";
see [The driver protocol].
All patterns with the prefix "query=", where query is a
non-empty string of letters from [a-z], are reserved and may be
interpreted as query operators.
Two query operators are currently supported: "file" and "pattern".
The query "file=path/to/file.go" matches the package or packages enclosing
the Go source file path/to/file.go. For example "file=~/go/src/fmt/print.go"
might return the packages "fmt" and "fmt [fmt.test]".
The query "pattern=string" causes "string" to be passed directly to
the underlying build tool. In most cases this is unnecessary,
but an application can use Load("pattern=" + x) as an escaping mechanism
to ensure that x is not interpreted as a query operator if it contains '='.
All other query operators are reserved for future use and currently
cause Load to report an error.
The Package struct provides basic information about the package, including
- ID, a unique identifier for the package in the returned set;
- GoFiles, the names of the package's Go source files;
- Imports, a map from source import strings to the Packages they name;
- Types, the type information for the package's exported symbols;
- Syntax, the parsed syntax trees for the package's source code; and
- TypesInfo, the result of a complete type-check of the package syntax trees.
(See the documentation for type Package for the complete list of fields
and more detailed descriptions.)
For example,
Load(nil, "bytes", "unicode...")
returns four Package structs describing the standard library packages
bytes, unicode, unicode/utf16, and unicode/utf8. Note that one pattern
can match multiple packages and that a package might be matched by
multiple patterns: in general it is not possible to determine which
packages correspond to which patterns.
Note that the list returned by Load contains only the packages matched
by the patterns. Their dependencies can be found by walking the import
graph using the Imports fields.
The Load function can be configured by passing a pointer to a Config as
the first argument. A nil Config is equivalent to the zero Config, which
causes Load to run in LoadFiles mode, collecting minimal information.
See the documentation for type Config for details.
As noted earlier, the Config.Mode controls the amount of detail
reported about the loaded packages. See the documentation for type LoadMode
for details.
Most tools should pass their command-line arguments (after any flags)
uninterpreted to [Load], so that it can interpret them
according to the conventions of the underlying build system.
See the Example function for typical usage.
# The driver protocol
[Load] may be used to load Go packages even in Go projects that use
alternative build systems, by installing an appropriate "driver"
program for the build system and specifying its location in the
GOPACKAGESDRIVER environment variable.
For example,
https://github.com/bazelbuild/rules_go/wiki/Editor-and-tool-integration
explains how to use the driver for Bazel.
The driver program is responsible for interpreting patterns in its
preferred notation and reporting information about the packages that
those patterns identify. Drivers must also support the special "file="
and "pattern=" patterns described above.
The patterns are provided as positional command-line arguments. A
JSON-encoded [DriverRequest] message providing additional information
is written to the driver's standard input. The driver must write a
JSON-encoded [DriverResponse] message to its standard output. (This
message differs from the JSON schema produced by 'go list'.)
*/
package packages // import "golang.org/x/tools/go/packages"
/*
Motivation and design considerations
The new package's design solves problems addressed by two existing
packages: go/build, which locates and describes packages, and
golang.org/x/tools/go/loader, which loads, parses and type-checks them.
The go/build.Package structure encodes too much of the 'go build' way
of organizing projects, leaving us in need of a data type that describes a
package of Go source code independent of the underlying build system.
We wanted something that works equally well with go build and vgo, and
also other build systems such as Bazel and Blaze, making it possible to
construct analysis tools that work in all these environments.
Tools such as errcheck and staticcheck were essentially unavailable to
the Go community at Google, and some of Google's internal tools for Go
are unavailable externally.
This new package provides a uniform way to obtain package metadata by
querying each of these build systems, optionally supporting their
preferred command-line notations for packages, so that tools integrate
neatly with users' build environments. The Metadata query function
executes an external query tool appropriate to the current workspace.
Loading packages always returns the complete import graph "all the way down",
even if all you want is information about a single package, because the query
mechanisms of all the build systems we currently support ({go,vgo} list, and
blaze/bazel aspect-based query) cannot provide detailed information
about one package without visiting all its dependencies too, so there is
no additional asymptotic cost to providing transitive information.
(This property might not be true of a hypothetical 5th build system.)
In calls to TypeCheck, all initial packages, and any package that
transitively depends on one of them, must be loaded from source.
Consider A->B->C->D->E: if A,C are initial, A,B,C must be loaded from
source; D may be loaded from export data, and E may not be loaded at all
(though it's possible that D's export data mentions it, so a
types.Package may be created for it and exposed.)
The old loader had a feature to suppress type-checking of function
bodies on a per-package basis, primarily intended to reduce the work of
obtaining type information for imported packages. Now that imports are
satisfied by export data, the optimization no longer seems necessary.
Despite some early attempts, the old loader did not exploit export data,
instead always using the equivalent of WholeProgram mode. This was due
to the complexity of mixing source and export data packages (now
resolved by the upward traversal mentioned above), and because export data
files were nearly always missing or stale. Now that 'go build' supports
caching, all the underlying build systems can guarantee to produce
export data in a reasonable (amortized) time.
Test "main" packages synthesized by the build system are now reported as
first-class packages, avoiding the need for clients (such as go/ssa) to
reinvent this generation logic.
One way in which go/packages is simpler than the old loader is in its
treatment of in-package tests. In-package tests are packages that
consist of all the files of the library under test, plus the test files.
The old loader constructed in-package tests by a two-phase process of
mutation called "augmentation": first it would construct and type check
all the ordinary library packages and type-check the packages that
depend on them; then it would add more (test) files to the package and
type-check again. This two-phase approach had four major problems:
1) in processing the tests, the loader modified the library package,
leaving no way for a client application to see both the test
package and the library package; one would mutate into the other.
2) because test files can declare additional methods on types defined in
the library portion of the package, the dispatch of method calls in
the library portion was affected by the presence of the test files.
This should have been a clue that the packages were logically
different.
3) this model of "augmentation" assumed at most one in-package test
per library package, which is true of projects using 'go build',
but not other build systems.
4) because of the two-phase nature of test processing, all packages that
import the library package had to be processed before augmentation,
forcing a "one-shot" API and preventing the client from calling Load
in several times in sequence as is now possible in WholeProgram mode.
(TypeCheck mode has a similar one-shot restriction for a different reason.)
Early drafts of this package supported "multi-shot" operation.
Although it allowed clients to make a sequence of calls (or concurrent
calls) to Load, building up the graph of Packages incrementally,
it was of marginal value: it complicated the API
(since it allowed some options to vary across calls but not others),
it complicated the implementation,
it cannot be made to work in Types mode, as explained above,
and it was less efficient than making one combined call (when this is possible).
Among the clients we have inspected, none made multiple calls to load
but could not be easily and satisfactorily modified to make only a single call.
However, applications changes may be required.
For example, the ssadump command loads the user-specified packages
and in addition the runtime package. It is tempting to simply append
"runtime" to the user-provided list, but that does not work if the user
specified an ad-hoc package such as [a.go b.go].
Instead, ssadump no longer requests the runtime package,
but seeks it among the dependencies of the user-specified packages,
and emits an error if it is not found.
Questions & Tasks
- Add GOARCH/GOOS?
They are not portable concepts, but could be made portable.
Our goal has been to allow users to express themselves using the conventions
of the underlying build system: if the build system honors GOARCH
during a build and during a metadata query, then so should
applications built atop that query mechanism.
Conversely, if the target architecture of the build is determined by
command-line flags, the application can pass the relevant
flags through to the build system using a command such as:
myapp -query_flag="--cpu=amd64" -query_flag="--os=darwin"
However, this approach is low-level, unwieldy, and non-portable.
GOOS and GOARCH seem important enough to warrant a dedicated option.
- How should we handle partial failures such as a mixture of good and
malformed patterns, existing and non-existent packages, successful and
failed builds, import failures, import cycles, and so on, in a call to
Load?
- Support bazel, blaze, and go1.10 list, not just go1.11 list.
- Handle (and test) various partial success cases, e.g.
a mixture of good packages and:
invalid patterns
nonexistent packages
empty packages
packages with malformed package or import declarations
unreadable files
import cycles
other parse errors
type errors
Make sure we record errors at the correct place in the graph.
- Missing packages among initial arguments are not reported.
Return bogus packages for them, like golist does.
- "undeclared name" errors (for example) are reported out of source file
order. I suspect this is due to the breadth-first resolution now used
by go/types. Is that a bug? Discuss with gri.
*/
| tools/go/packages/doc.go/0 | {
"file_path": "tools/go/packages/doc.go",
"repo_id": "tools",
"token_count": 2794
} | 706 |
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package packagestest_test
import (
"path/filepath"
"testing"
"golang.org/x/tools/go/packages/packagestest"
)
func TestGOPATHExport(t *testing.T) {
exported := packagestest.Export(t, packagestest.GOPATH, testdata)
defer exported.Cleanup()
// Check that the cfg contains all the right bits
var expectDir = filepath.Join(exported.Temp(), "fake1", "src")
if exported.Config.Dir != expectDir {
t.Errorf("Got working directory %v expected %v", exported.Config.Dir, expectDir)
}
checkFiles(t, exported, []fileTest{
{"golang.org/fake1", "a.go", "fake1/src/golang.org/fake1/a.go", checkLink("testdata/a.go")},
{"golang.org/fake1", "b.go", "fake1/src/golang.org/fake1/b.go", checkContent("package fake1")},
{"golang.org/fake2", "other/a.go", "fake2/src/golang.org/fake2/other/a.go", checkContent("package fake2")},
{"golang.org/fake2/v2", "other/a.go", "fake2_v2/src/golang.org/fake2/v2/other/a.go", checkContent("package fake2")},
})
}
| tools/go/packages/packagestest/gopath_test.go/0 | {
"file_path": "tools/go/packages/packagestest/gopath_test.go",
"repo_id": "tools",
"token_count": 434
} | 707 |
package fake1
type ATestType string //@check("ATestType","ATestType")
| tools/go/packages/packagestest/testdata/test_test.go/0 | {
"file_path": "tools/go/packages/packagestest/testdata/test_test.go",
"repo_id": "tools",
"token_count": 23
} | 708 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssa
// This file implements the CREATE phase of SSA construction.
// See builder.go for explanation.
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"os"
"sync"
"golang.org/x/tools/internal/versions"
)
// NewProgram returns a new SSA Program.
//
// mode controls diagnostics and checking during SSA construction.
//
// To construct an SSA program:
//
// - Call NewProgram to create an empty Program.
// - Call CreatePackage providing typed syntax for each package
// you want to build, and call it with types but not
// syntax for each of those package's direct dependencies.
// - Call [Package.Build] on each syntax package you wish to build,
// or [Program.Build] to build all of them.
//
// See the Example tests for simple examples.
func NewProgram(fset *token.FileSet, mode BuilderMode) *Program {
return &Program{
Fset: fset,
imported: make(map[string]*Package),
packages: make(map[*types.Package]*Package),
mode: mode,
canon: newCanonizer(),
ctxt: types.NewContext(),
}
}
// memberFromObject populates package pkg with a member for the
// typechecker object obj.
//
// For objects from Go source code, syntax is the associated syntax
// tree (for funcs and vars only) and goversion defines the
// appropriate interpretation; they will be used during the build
// phase.
func memberFromObject(pkg *Package, obj types.Object, syntax ast.Node, goversion string) {
name := obj.Name()
switch obj := obj.(type) {
case *types.Builtin:
if pkg.Pkg != types.Unsafe {
panic("unexpected builtin object: " + obj.String())
}
case *types.TypeName:
if name != "_" {
pkg.Members[name] = &Type{
object: obj,
pkg: pkg,
}
}
case *types.Const:
c := &NamedConst{
object: obj,
Value: NewConst(obj.Val(), obj.Type()),
pkg: pkg,
}
pkg.objects[obj] = c
if name != "_" {
pkg.Members[name] = c
}
case *types.Var:
g := &Global{
Pkg: pkg,
name: name,
object: obj,
typ: types.NewPointer(obj.Type()), // address
pos: obj.Pos(),
}
pkg.objects[obj] = g
if name != "_" {
pkg.Members[name] = g
}
case *types.Func:
sig := obj.Type().(*types.Signature)
if sig.Recv() == nil && name == "init" {
pkg.ninit++
name = fmt.Sprintf("init#%d", pkg.ninit)
}
fn := createFunction(pkg.Prog, obj, name, syntax, pkg.info, goversion)
fn.Pkg = pkg
pkg.created = append(pkg.created, fn)
pkg.objects[obj] = fn
if name != "_" && sig.Recv() == nil {
pkg.Members[name] = fn // package-level function
}
default: // (incl. *types.Package)
panic("unexpected Object type: " + obj.String())
}
}
// createFunction creates a function or method. It supports both
// CreatePackage (with or without syntax) and the on-demand creation
// of methods in non-created packages based on their types.Func.
func createFunction(prog *Program, obj *types.Func, name string, syntax ast.Node, info *types.Info, goversion string) *Function {
sig := obj.Type().(*types.Signature)
// Collect type parameters.
var tparams *types.TypeParamList
if rtparams := sig.RecvTypeParams(); rtparams.Len() > 0 {
tparams = rtparams // method of generic type
} else if sigparams := sig.TypeParams(); sigparams.Len() > 0 {
tparams = sigparams // generic function
}
/* declared function/method (from syntax or export data) */
fn := &Function{
name: name,
object: obj,
Signature: sig,
build: (*builder).buildFromSyntax,
syntax: syntax,
info: info,
goversion: goversion,
pos: obj.Pos(),
Pkg: nil, // may be set by caller
Prog: prog,
typeparams: tparams,
}
if fn.syntax == nil {
fn.Synthetic = "from type information"
fn.build = (*builder).buildParamsOnly
}
if tparams.Len() > 0 {
fn.generic = new(generic)
}
return fn
}
// membersFromDecl populates package pkg with members for each
// typechecker object (var, func, const or type) associated with the
// specified decl.
func membersFromDecl(pkg *Package, decl ast.Decl, goversion string) {
switch decl := decl.(type) {
case *ast.GenDecl: // import, const, type or var
switch decl.Tok {
case token.CONST:
for _, spec := range decl.Specs {
for _, id := range spec.(*ast.ValueSpec).Names {
memberFromObject(pkg, pkg.info.Defs[id], nil, "")
}
}
case token.VAR:
for _, spec := range decl.Specs {
for _, rhs := range spec.(*ast.ValueSpec).Values {
pkg.initVersion[rhs] = goversion
}
for _, id := range spec.(*ast.ValueSpec).Names {
memberFromObject(pkg, pkg.info.Defs[id], spec, goversion)
}
}
case token.TYPE:
for _, spec := range decl.Specs {
id := spec.(*ast.TypeSpec).Name
memberFromObject(pkg, pkg.info.Defs[id], nil, "")
}
}
case *ast.FuncDecl:
id := decl.Name
memberFromObject(pkg, pkg.info.Defs[id], decl, goversion)
}
}
// CreatePackage creates and returns an SSA Package from the
// specified type-checked, error-free file ASTs, and populates its
// Members mapping.
//
// importable determines whether this package should be returned by a
// subsequent call to ImportedPackage(pkg.Path()).
//
// The real work of building SSA form for each function is not done
// until a subsequent call to Package.Build.
//
// CreatePackage should not be called after building any package in
// the program.
func (prog *Program) CreatePackage(pkg *types.Package, files []*ast.File, info *types.Info, importable bool) *Package {
// TODO(adonovan): assert that no package has yet been built.
if pkg == nil {
panic("nil pkg") // otherwise pkg.Scope below returns types.Universe!
}
p := &Package{
Prog: prog,
Members: make(map[string]Member),
objects: make(map[types.Object]Member),
Pkg: pkg,
syntax: info != nil,
// transient values (cleared after Package.Build)
info: info,
files: files,
initVersion: make(map[ast.Expr]string),
}
/* synthesized package initializer */
p.init = &Function{
name: "init",
Signature: new(types.Signature),
Synthetic: "package initializer",
Pkg: p,
Prog: prog,
build: (*builder).buildPackageInit,
info: p.info,
goversion: "", // See Package.build for details.
}
p.Members[p.init.name] = p.init
p.created = append(p.created, p.init)
// Allocate all package members: vars, funcs, consts and types.
if len(files) > 0 {
// Go source package.
for _, file := range files {
goversion := versions.Lang(versions.FileVersion(p.info, file))
for _, decl := range file.Decls {
membersFromDecl(p, decl, goversion)
}
}
} else {
// GC-compiled binary package (or "unsafe")
// No code.
// No position information.
scope := p.Pkg.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
memberFromObject(p, obj, nil, "")
if obj, ok := obj.(*types.TypeName); ok {
// No Unalias: aliases should not duplicate methods.
if named, ok := obj.Type().(*types.Named); ok {
for i, n := 0, named.NumMethods(); i < n; i++ {
memberFromObject(p, named.Method(i), nil, "")
}
}
}
}
}
if prog.mode&BareInits == 0 {
// Add initializer guard variable.
initguard := &Global{
Pkg: p,
name: "init$guard",
typ: types.NewPointer(tBool),
}
p.Members[initguard.Name()] = initguard
}
if prog.mode&GlobalDebug != 0 {
p.SetDebugMode(true)
}
if prog.mode&PrintPackages != 0 {
printMu.Lock()
p.WriteTo(os.Stdout)
printMu.Unlock()
}
if importable {
prog.imported[p.Pkg.Path()] = p
}
prog.packages[p.Pkg] = p
return p
}
// printMu serializes printing of Packages/Functions to stdout.
var printMu sync.Mutex
// AllPackages returns a new slice containing all packages created by
// prog.CreatePackage in unspecified order.
func (prog *Program) AllPackages() []*Package {
pkgs := make([]*Package, 0, len(prog.packages))
for _, pkg := range prog.packages {
pkgs = append(pkgs, pkg)
}
return pkgs
}
// ImportedPackage returns the importable Package whose PkgPath
// is path, or nil if no such Package has been created.
//
// A parameter to CreatePackage determines whether a package should be
// considered importable. For example, no import declaration can resolve
// to the ad-hoc main package created by 'go build foo.go'.
//
// TODO(adonovan): rethink this function and the "importable" concept;
// most packages are importable. This function assumes that all
// types.Package.Path values are unique within the ssa.Program, which is
// false---yet this function remains very convenient.
// Clients should use (*Program).Package instead where possible.
// SSA doesn't really need a string-keyed map of packages.
//
// Furthermore, the graph of packages may contain multiple variants
// (e.g. "p" vs "p as compiled for q.test"), and each has a different
// view of its dependencies.
func (prog *Program) ImportedPackage(path string) *Package {
return prog.imported[path]
}
| tools/go/ssa/create.go/0 | {
"file_path": "tools/go/ssa/create.go",
"repo_id": "tools",
"token_count": 3334
} | 709 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package interp
import (
"bytes"
"fmt"
"go/constant"
"go/token"
"go/types"
"os"
"reflect"
"strings"
"sync"
"unsafe"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/internal/aliases"
"golang.org/x/tools/internal/typeparams"
)
// If the target program panics, the interpreter panics with this type.
type targetPanic struct {
v value
}
func (p targetPanic) String() string {
return toString(p.v)
}
// If the target program calls exit, the interpreter panics with this type.
type exitPanic int
// constValue returns the value of the constant with the
// dynamic type tag appropriate for c.Type().
func constValue(c *ssa.Const) value {
if c.Value == nil {
return zero(c.Type()) // typed zero
}
// c is not a type parameter so it's underlying type is basic.
if t, ok := c.Type().Underlying().(*types.Basic); ok {
// TODO(adonovan): eliminate untyped constants from SSA form.
switch t.Kind() {
case types.Bool, types.UntypedBool:
return constant.BoolVal(c.Value)
case types.Int, types.UntypedInt:
// Assume sizeof(int) is same on host and target.
return int(c.Int64())
case types.Int8:
return int8(c.Int64())
case types.Int16:
return int16(c.Int64())
case types.Int32, types.UntypedRune:
return int32(c.Int64())
case types.Int64:
return c.Int64()
case types.Uint:
// Assume sizeof(uint) is same on host and target.
return uint(c.Uint64())
case types.Uint8:
return uint8(c.Uint64())
case types.Uint16:
return uint16(c.Uint64())
case types.Uint32:
return uint32(c.Uint64())
case types.Uint64:
return c.Uint64()
case types.Uintptr:
// Assume sizeof(uintptr) is same on host and target.
return uintptr(c.Uint64())
case types.Float32:
return float32(c.Float64())
case types.Float64, types.UntypedFloat:
return c.Float64()
case types.Complex64:
return complex64(c.Complex128())
case types.Complex128, types.UntypedComplex:
return c.Complex128()
case types.String, types.UntypedString:
if c.Value.Kind() == constant.String {
return constant.StringVal(c.Value)
}
return string(rune(c.Int64()))
}
}
panic(fmt.Sprintf("constValue: %s", c))
}
// fitsInt returns true if x fits in type int according to sizes.
func fitsInt(x int64, sizes types.Sizes) bool {
intSize := sizes.Sizeof(types.Typ[types.Int])
if intSize < sizes.Sizeof(types.Typ[types.Int64]) {
maxInt := int64(1)<<((intSize*8)-1) - 1
minInt := -int64(1) << ((intSize * 8) - 1)
return minInt <= x && x <= maxInt
}
return true
}
// asInt64 converts x, which must be an integer, to an int64.
//
// Callers that need a value directly usable as an int should combine this with fitsInt().
func asInt64(x value) int64 {
switch x := x.(type) {
case int:
return int64(x)
case int8:
return int64(x)
case int16:
return int64(x)
case int32:
return int64(x)
case int64:
return x
case uint:
return int64(x)
case uint8:
return int64(x)
case uint16:
return int64(x)
case uint32:
return int64(x)
case uint64:
return int64(x)
case uintptr:
return int64(x)
}
panic(fmt.Sprintf("cannot convert %T to int64", x))
}
// asUint64 converts x, which must be an unsigned integer, to a uint64
// suitable for use as a bitwise shift count.
func asUint64(x value) uint64 {
switch x := x.(type) {
case uint:
return uint64(x)
case uint8:
return uint64(x)
case uint16:
return uint64(x)
case uint32:
return uint64(x)
case uint64:
return x
case uintptr:
return uint64(x)
}
panic(fmt.Sprintf("cannot convert %T to uint64", x))
}
// asUnsigned returns the value of x, which must be an integer type, as its equivalent unsigned type,
// and returns true if x is non-negative.
func asUnsigned(x value) (value, bool) {
switch x := x.(type) {
case int:
return uint(x), x >= 0
case int8:
return uint8(x), x >= 0
case int16:
return uint16(x), x >= 0
case int32:
return uint32(x), x >= 0
case int64:
return uint64(x), x >= 0
case uint, uint8, uint32, uint64, uintptr:
return x, true
}
panic(fmt.Sprintf("cannot convert %T to unsigned", x))
}
// zero returns a new "zero" value of the specified type.
func zero(t types.Type) value {
switch t := t.(type) {
case *types.Basic:
if t.Kind() == types.UntypedNil {
panic("untyped nil has no zero value")
}
if t.Info()&types.IsUntyped != 0 {
// TODO(adonovan): make it an invariant that
// this is unreachable. Currently some
// constants have 'untyped' types when they
// should be defaulted by the typechecker.
t = types.Default(t).(*types.Basic)
}
switch t.Kind() {
case types.Bool:
return false
case types.Int:
return int(0)
case types.Int8:
return int8(0)
case types.Int16:
return int16(0)
case types.Int32:
return int32(0)
case types.Int64:
return int64(0)
case types.Uint:
return uint(0)
case types.Uint8:
return uint8(0)
case types.Uint16:
return uint16(0)
case types.Uint32:
return uint32(0)
case types.Uint64:
return uint64(0)
case types.Uintptr:
return uintptr(0)
case types.Float32:
return float32(0)
case types.Float64:
return float64(0)
case types.Complex64:
return complex64(0)
case types.Complex128:
return complex128(0)
case types.String:
return ""
case types.UnsafePointer:
return unsafe.Pointer(nil)
default:
panic(fmt.Sprint("zero for unexpected type:", t))
}
case *types.Pointer:
return (*value)(nil)
case *types.Array:
a := make(array, t.Len())
for i := range a {
a[i] = zero(t.Elem())
}
return a
case *types.Named:
return zero(t.Underlying())
case *aliases.Alias:
return zero(aliases.Unalias(t))
case *types.Interface:
return iface{} // nil type, methodset and value
case *types.Slice:
return []value(nil)
case *types.Struct:
s := make(structure, t.NumFields())
for i := range s {
s[i] = zero(t.Field(i).Type())
}
return s
case *types.Tuple:
if t.Len() == 1 {
return zero(t.At(0).Type())
}
s := make(tuple, t.Len())
for i := range s {
s[i] = zero(t.At(i).Type())
}
return s
case *types.Chan:
return chan value(nil)
case *types.Map:
if usesBuiltinMap(t.Key()) {
return map[value]value(nil)
}
return (*hashmap)(nil)
case *types.Signature:
return (*ssa.Function)(nil)
}
panic(fmt.Sprint("zero: unexpected ", t))
}
// slice returns x[lo:hi:max]. Any of lo, hi and max may be nil.
func slice(x, lo, hi, max value) value {
var Len, Cap int
switch x := x.(type) {
case string:
Len = len(x)
case []value:
Len = len(x)
Cap = cap(x)
case *value: // *array
a := (*x).(array)
Len = len(a)
Cap = cap(a)
}
l := int64(0)
if lo != nil {
l = asInt64(lo)
}
h := int64(Len)
if hi != nil {
h = asInt64(hi)
}
m := int64(Cap)
if max != nil {
m = asInt64(max)
}
switch x := x.(type) {
case string:
return x[l:h]
case []value:
return x[l:h:m]
case *value: // *array
a := (*x).(array)
return []value(a)[l:h:m]
}
panic(fmt.Sprintf("slice: unexpected X type: %T", x))
}
// lookup returns x[idx] where x is a map.
func lookup(instr *ssa.Lookup, x, idx value) value {
switch x := x.(type) { // map or string
case map[value]value, *hashmap:
var v value
var ok bool
switch x := x.(type) {
case map[value]value:
v, ok = x[idx]
case *hashmap:
v = x.lookup(idx.(hashable))
ok = v != nil
}
if !ok {
v = zero(instr.X.Type().Underlying().(*types.Map).Elem())
}
if instr.CommaOk {
v = tuple{v, ok}
}
return v
}
panic(fmt.Sprintf("unexpected x type in Lookup: %T", x))
}
// binop implements all arithmetic and logical binary operators for
// numeric datatypes and strings. Both operands must have identical
// dynamic type.
func binop(op token.Token, t types.Type, x, y value) value {
switch op {
case token.ADD:
switch x.(type) {
case int:
return x.(int) + y.(int)
case int8:
return x.(int8) + y.(int8)
case int16:
return x.(int16) + y.(int16)
case int32:
return x.(int32) + y.(int32)
case int64:
return x.(int64) + y.(int64)
case uint:
return x.(uint) + y.(uint)
case uint8:
return x.(uint8) + y.(uint8)
case uint16:
return x.(uint16) + y.(uint16)
case uint32:
return x.(uint32) + y.(uint32)
case uint64:
return x.(uint64) + y.(uint64)
case uintptr:
return x.(uintptr) + y.(uintptr)
case float32:
return x.(float32) + y.(float32)
case float64:
return x.(float64) + y.(float64)
case complex64:
return x.(complex64) + y.(complex64)
case complex128:
return x.(complex128) + y.(complex128)
case string:
return x.(string) + y.(string)
}
case token.SUB:
switch x.(type) {
case int:
return x.(int) - y.(int)
case int8:
return x.(int8) - y.(int8)
case int16:
return x.(int16) - y.(int16)
case int32:
return x.(int32) - y.(int32)
case int64:
return x.(int64) - y.(int64)
case uint:
return x.(uint) - y.(uint)
case uint8:
return x.(uint8) - y.(uint8)
case uint16:
return x.(uint16) - y.(uint16)
case uint32:
return x.(uint32) - y.(uint32)
case uint64:
return x.(uint64) - y.(uint64)
case uintptr:
return x.(uintptr) - y.(uintptr)
case float32:
return x.(float32) - y.(float32)
case float64:
return x.(float64) - y.(float64)
case complex64:
return x.(complex64) - y.(complex64)
case complex128:
return x.(complex128) - y.(complex128)
}
case token.MUL:
switch x.(type) {
case int:
return x.(int) * y.(int)
case int8:
return x.(int8) * y.(int8)
case int16:
return x.(int16) * y.(int16)
case int32:
return x.(int32) * y.(int32)
case int64:
return x.(int64) * y.(int64)
case uint:
return x.(uint) * y.(uint)
case uint8:
return x.(uint8) * y.(uint8)
case uint16:
return x.(uint16) * y.(uint16)
case uint32:
return x.(uint32) * y.(uint32)
case uint64:
return x.(uint64) * y.(uint64)
case uintptr:
return x.(uintptr) * y.(uintptr)
case float32:
return x.(float32) * y.(float32)
case float64:
return x.(float64) * y.(float64)
case complex64:
return x.(complex64) * y.(complex64)
case complex128:
return x.(complex128) * y.(complex128)
}
case token.QUO:
switch x.(type) {
case int:
return x.(int) / y.(int)
case int8:
return x.(int8) / y.(int8)
case int16:
return x.(int16) / y.(int16)
case int32:
return x.(int32) / y.(int32)
case int64:
return x.(int64) / y.(int64)
case uint:
return x.(uint) / y.(uint)
case uint8:
return x.(uint8) / y.(uint8)
case uint16:
return x.(uint16) / y.(uint16)
case uint32:
return x.(uint32) / y.(uint32)
case uint64:
return x.(uint64) / y.(uint64)
case uintptr:
return x.(uintptr) / y.(uintptr)
case float32:
return x.(float32) / y.(float32)
case float64:
return x.(float64) / y.(float64)
case complex64:
return x.(complex64) / y.(complex64)
case complex128:
return x.(complex128) / y.(complex128)
}
case token.REM:
switch x.(type) {
case int:
return x.(int) % y.(int)
case int8:
return x.(int8) % y.(int8)
case int16:
return x.(int16) % y.(int16)
case int32:
return x.(int32) % y.(int32)
case int64:
return x.(int64) % y.(int64)
case uint:
return x.(uint) % y.(uint)
case uint8:
return x.(uint8) % y.(uint8)
case uint16:
return x.(uint16) % y.(uint16)
case uint32:
return x.(uint32) % y.(uint32)
case uint64:
return x.(uint64) % y.(uint64)
case uintptr:
return x.(uintptr) % y.(uintptr)
}
case token.AND:
switch x.(type) {
case int:
return x.(int) & y.(int)
case int8:
return x.(int8) & y.(int8)
case int16:
return x.(int16) & y.(int16)
case int32:
return x.(int32) & y.(int32)
case int64:
return x.(int64) & y.(int64)
case uint:
return x.(uint) & y.(uint)
case uint8:
return x.(uint8) & y.(uint8)
case uint16:
return x.(uint16) & y.(uint16)
case uint32:
return x.(uint32) & y.(uint32)
case uint64:
return x.(uint64) & y.(uint64)
case uintptr:
return x.(uintptr) & y.(uintptr)
}
case token.OR:
switch x.(type) {
case int:
return x.(int) | y.(int)
case int8:
return x.(int8) | y.(int8)
case int16:
return x.(int16) | y.(int16)
case int32:
return x.(int32) | y.(int32)
case int64:
return x.(int64) | y.(int64)
case uint:
return x.(uint) | y.(uint)
case uint8:
return x.(uint8) | y.(uint8)
case uint16:
return x.(uint16) | y.(uint16)
case uint32:
return x.(uint32) | y.(uint32)
case uint64:
return x.(uint64) | y.(uint64)
case uintptr:
return x.(uintptr) | y.(uintptr)
}
case token.XOR:
switch x.(type) {
case int:
return x.(int) ^ y.(int)
case int8:
return x.(int8) ^ y.(int8)
case int16:
return x.(int16) ^ y.(int16)
case int32:
return x.(int32) ^ y.(int32)
case int64:
return x.(int64) ^ y.(int64)
case uint:
return x.(uint) ^ y.(uint)
case uint8:
return x.(uint8) ^ y.(uint8)
case uint16:
return x.(uint16) ^ y.(uint16)
case uint32:
return x.(uint32) ^ y.(uint32)
case uint64:
return x.(uint64) ^ y.(uint64)
case uintptr:
return x.(uintptr) ^ y.(uintptr)
}
case token.AND_NOT:
switch x.(type) {
case int:
return x.(int) &^ y.(int)
case int8:
return x.(int8) &^ y.(int8)
case int16:
return x.(int16) &^ y.(int16)
case int32:
return x.(int32) &^ y.(int32)
case int64:
return x.(int64) &^ y.(int64)
case uint:
return x.(uint) &^ y.(uint)
case uint8:
return x.(uint8) &^ y.(uint8)
case uint16:
return x.(uint16) &^ y.(uint16)
case uint32:
return x.(uint32) &^ y.(uint32)
case uint64:
return x.(uint64) &^ y.(uint64)
case uintptr:
return x.(uintptr) &^ y.(uintptr)
}
case token.SHL:
u, ok := asUnsigned(y)
if !ok {
panic("negative shift amount")
}
y := asUint64(u)
switch x.(type) {
case int:
return x.(int) << y
case int8:
return x.(int8) << y
case int16:
return x.(int16) << y
case int32:
return x.(int32) << y
case int64:
return x.(int64) << y
case uint:
return x.(uint) << y
case uint8:
return x.(uint8) << y
case uint16:
return x.(uint16) << y
case uint32:
return x.(uint32) << y
case uint64:
return x.(uint64) << y
case uintptr:
return x.(uintptr) << y
}
case token.SHR:
u, ok := asUnsigned(y)
if !ok {
panic("negative shift amount")
}
y := asUint64(u)
switch x.(type) {
case int:
return x.(int) >> y
case int8:
return x.(int8) >> y
case int16:
return x.(int16) >> y
case int32:
return x.(int32) >> y
case int64:
return x.(int64) >> y
case uint:
return x.(uint) >> y
case uint8:
return x.(uint8) >> y
case uint16:
return x.(uint16) >> y
case uint32:
return x.(uint32) >> y
case uint64:
return x.(uint64) >> y
case uintptr:
return x.(uintptr) >> y
}
case token.LSS:
switch x.(type) {
case int:
return x.(int) < y.(int)
case int8:
return x.(int8) < y.(int8)
case int16:
return x.(int16) < y.(int16)
case int32:
return x.(int32) < y.(int32)
case int64:
return x.(int64) < y.(int64)
case uint:
return x.(uint) < y.(uint)
case uint8:
return x.(uint8) < y.(uint8)
case uint16:
return x.(uint16) < y.(uint16)
case uint32:
return x.(uint32) < y.(uint32)
case uint64:
return x.(uint64) < y.(uint64)
case uintptr:
return x.(uintptr) < y.(uintptr)
case float32:
return x.(float32) < y.(float32)
case float64:
return x.(float64) < y.(float64)
case string:
return x.(string) < y.(string)
}
case token.LEQ:
switch x.(type) {
case int:
return x.(int) <= y.(int)
case int8:
return x.(int8) <= y.(int8)
case int16:
return x.(int16) <= y.(int16)
case int32:
return x.(int32) <= y.(int32)
case int64:
return x.(int64) <= y.(int64)
case uint:
return x.(uint) <= y.(uint)
case uint8:
return x.(uint8) <= y.(uint8)
case uint16:
return x.(uint16) <= y.(uint16)
case uint32:
return x.(uint32) <= y.(uint32)
case uint64:
return x.(uint64) <= y.(uint64)
case uintptr:
return x.(uintptr) <= y.(uintptr)
case float32:
return x.(float32) <= y.(float32)
case float64:
return x.(float64) <= y.(float64)
case string:
return x.(string) <= y.(string)
}
case token.EQL:
return eqnil(t, x, y)
case token.NEQ:
return !eqnil(t, x, y)
case token.GTR:
switch x.(type) {
case int:
return x.(int) > y.(int)
case int8:
return x.(int8) > y.(int8)
case int16:
return x.(int16) > y.(int16)
case int32:
return x.(int32) > y.(int32)
case int64:
return x.(int64) > y.(int64)
case uint:
return x.(uint) > y.(uint)
case uint8:
return x.(uint8) > y.(uint8)
case uint16:
return x.(uint16) > y.(uint16)
case uint32:
return x.(uint32) > y.(uint32)
case uint64:
return x.(uint64) > y.(uint64)
case uintptr:
return x.(uintptr) > y.(uintptr)
case float32:
return x.(float32) > y.(float32)
case float64:
return x.(float64) > y.(float64)
case string:
return x.(string) > y.(string)
}
case token.GEQ:
switch x.(type) {
case int:
return x.(int) >= y.(int)
case int8:
return x.(int8) >= y.(int8)
case int16:
return x.(int16) >= y.(int16)
case int32:
return x.(int32) >= y.(int32)
case int64:
return x.(int64) >= y.(int64)
case uint:
return x.(uint) >= y.(uint)
case uint8:
return x.(uint8) >= y.(uint8)
case uint16:
return x.(uint16) >= y.(uint16)
case uint32:
return x.(uint32) >= y.(uint32)
case uint64:
return x.(uint64) >= y.(uint64)
case uintptr:
return x.(uintptr) >= y.(uintptr)
case float32:
return x.(float32) >= y.(float32)
case float64:
return x.(float64) >= y.(float64)
case string:
return x.(string) >= y.(string)
}
}
panic(fmt.Sprintf("invalid binary op: %T %s %T", x, op, y))
}
// eqnil returns the comparison x == y using the equivalence relation
// appropriate for type t.
// If t is a reference type, at most one of x or y may be a nil value
// of that type.
func eqnil(t types.Type, x, y value) bool {
switch t.Underlying().(type) {
case *types.Map, *types.Signature, *types.Slice:
// Since these types don't support comparison,
// one of the operands must be a literal nil.
switch x := x.(type) {
case *hashmap:
return (x != nil) == (y.(*hashmap) != nil)
case map[value]value:
return (x != nil) == (y.(map[value]value) != nil)
case *ssa.Function:
switch y := y.(type) {
case *ssa.Function:
return (x != nil) == (y != nil)
case *closure:
return true
}
case *closure:
return (x != nil) == (y.(*ssa.Function) != nil)
case []value:
return (x != nil) == (y.([]value) != nil)
}
panic(fmt.Sprintf("eqnil(%s): illegal dynamic type: %T", t, x))
}
return equals(t, x, y)
}
func unop(instr *ssa.UnOp, x value) value {
switch instr.Op {
case token.ARROW: // receive
v, ok := <-x.(chan value)
if !ok {
v = zero(instr.X.Type().Underlying().(*types.Chan).Elem())
}
if instr.CommaOk {
v = tuple{v, ok}
}
return v
case token.SUB:
switch x := x.(type) {
case int:
return -x
case int8:
return -x
case int16:
return -x
case int32:
return -x
case int64:
return -x
case uint:
return -x
case uint8:
return -x
case uint16:
return -x
case uint32:
return -x
case uint64:
return -x
case uintptr:
return -x
case float32:
return -x
case float64:
return -x
case complex64:
return -x
case complex128:
return -x
}
case token.MUL:
return load(typeparams.MustDeref(instr.X.Type()), x.(*value))
case token.NOT:
return !x.(bool)
case token.XOR:
switch x := x.(type) {
case int:
return ^x
case int8:
return ^x
case int16:
return ^x
case int32:
return ^x
case int64:
return ^x
case uint:
return ^x
case uint8:
return ^x
case uint16:
return ^x
case uint32:
return ^x
case uint64:
return ^x
case uintptr:
return ^x
}
}
panic(fmt.Sprintf("invalid unary op %s %T", instr.Op, x))
}
// typeAssert checks whether dynamic type of itf is instr.AssertedType.
// It returns the extracted value on success, and panics on failure,
// unless instr.CommaOk, in which case it always returns a "value,ok" tuple.
func typeAssert(i *interpreter, instr *ssa.TypeAssert, itf iface) value {
var v value
err := ""
if itf.t == nil {
err = fmt.Sprintf("interface conversion: interface is nil, not %s", instr.AssertedType)
} else if idst, ok := instr.AssertedType.Underlying().(*types.Interface); ok {
v = itf
err = checkInterface(i, idst, itf)
} else if types.Identical(itf.t, instr.AssertedType) {
v = itf.v // extract value
} else {
err = fmt.Sprintf("interface conversion: interface is %s, not %s", itf.t, instr.AssertedType)
}
// Note: if instr.Underlying==true ever becomes reachable from interp check that
// types.Identical(itf.t.Underlying(), instr.AssertedType)
if err != "" {
if !instr.CommaOk {
panic(err)
}
return tuple{zero(instr.AssertedType), false}
}
if instr.CommaOk {
return tuple{v, true}
}
return v
}
// If CapturedOutput is non-nil, all writes by the interpreted program
// to file descriptors 1 and 2 will also be written to CapturedOutput.
//
// (The $GOROOT/test system requires that the test be considered a
// failure if "BUG" appears in the combined stdout/stderr output, even
// if it exits zero. This is a global variable shared by all
// interpreters in the same process.)
var CapturedOutput *bytes.Buffer
var capturedOutputMu sync.Mutex
// write writes bytes b to the target program's standard output.
// The print/println built-ins and the write() system call funnel
// through here so they can be captured by the test driver.
func print(b []byte) (int, error) {
if CapturedOutput != nil {
capturedOutputMu.Lock()
CapturedOutput.Write(b) // ignore errors
capturedOutputMu.Unlock()
}
return os.Stdout.Write(b)
}
// callBuiltin interprets a call to builtin fn with arguments args,
// returning its result.
func callBuiltin(caller *frame, callpos token.Pos, fn *ssa.Builtin, args []value) value {
switch fn.Name() {
case "append":
if len(args) == 1 {
return args[0]
}
if s, ok := args[1].(string); ok {
// append([]byte, ...string) []byte
arg0 := args[0].([]value)
for i := 0; i < len(s); i++ {
arg0 = append(arg0, s[i])
}
return arg0
}
// append([]T, ...[]T) []T
return append(args[0].([]value), args[1].([]value)...)
case "copy": // copy([]T, []T) int or copy([]byte, string) int
src := args[1]
if _, ok := src.(string); ok {
params := fn.Type().(*types.Signature).Params()
src = conv(params.At(0).Type(), params.At(1).Type(), src)
}
return copy(args[0].([]value), src.([]value))
case "close": // close(chan T)
close(args[0].(chan value))
return nil
case "delete": // delete(map[K]value, K)
switch m := args[0].(type) {
case map[value]value:
delete(m, args[1])
case *hashmap:
m.delete(args[1].(hashable))
default:
panic(fmt.Sprintf("illegal map type: %T", m))
}
return nil
case "print", "println": // print(any, ...)
ln := fn.Name() == "println"
var buf bytes.Buffer
for i, arg := range args {
if i > 0 && ln {
buf.WriteRune(' ')
}
buf.WriteString(toString(arg))
}
if ln {
buf.WriteRune('\n')
}
print(buf.Bytes())
return nil
case "len":
switch x := args[0].(type) {
case string:
return len(x)
case array:
return len(x)
case *value:
return len((*x).(array))
case []value:
return len(x)
case map[value]value:
return len(x)
case *hashmap:
return x.len()
case chan value:
return len(x)
default:
panic(fmt.Sprintf("len: illegal operand: %T", x))
}
case "cap":
switch x := args[0].(type) {
case array:
return cap(x)
case *value:
return cap((*x).(array))
case []value:
return cap(x)
case chan value:
return cap(x)
default:
panic(fmt.Sprintf("cap: illegal operand: %T", x))
}
case "min":
return foldLeft(min, args)
case "max":
return foldLeft(max, args)
case "real":
switch c := args[0].(type) {
case complex64:
return real(c)
case complex128:
return real(c)
default:
panic(fmt.Sprintf("real: illegal operand: %T", c))
}
case "imag":
switch c := args[0].(type) {
case complex64:
return imag(c)
case complex128:
return imag(c)
default:
panic(fmt.Sprintf("imag: illegal operand: %T", c))
}
case "complex":
switch f := args[0].(type) {
case float32:
return complex(f, args[1].(float32))
case float64:
return complex(f, args[1].(float64))
default:
panic(fmt.Sprintf("complex: illegal operand: %T", f))
}
case "panic":
// ssa.Panic handles most cases; this is only for "go
// panic" or "defer panic".
panic(targetPanic{args[0]})
case "recover":
return doRecover(caller)
case "ssa:wrapnilchk":
recv := args[0]
if recv.(*value) == nil {
recvType := args[1]
methodName := args[2]
panic(fmt.Sprintf("value method (%s).%s called using nil *%s pointer",
recvType, methodName, recvType))
}
return recv
case "ssa:deferstack":
return &caller.defers
}
panic("unknown built-in: " + fn.Name())
}
func rangeIter(x value, t types.Type) iter {
switch x := x.(type) {
case map[value]value:
return &mapIter{iter: reflect.ValueOf(x).MapRange()}
case *hashmap:
return &hashmapIter{iter: reflect.ValueOf(x.entries()).MapRange()}
case string:
return &stringIter{Reader: strings.NewReader(x)}
}
panic(fmt.Sprintf("cannot range over %T", x))
}
// widen widens a basic typed value x to the widest type of its
// category, one of:
//
// bool, int64, uint64, float64, complex128, string.
//
// This is inefficient but reduces the size of the cross-product of
// cases we have to consider.
func widen(x value) value {
switch y := x.(type) {
case bool, int64, uint64, float64, complex128, string, unsafe.Pointer:
return x
case int:
return int64(y)
case int8:
return int64(y)
case int16:
return int64(y)
case int32:
return int64(y)
case uint:
return uint64(y)
case uint8:
return uint64(y)
case uint16:
return uint64(y)
case uint32:
return uint64(y)
case uintptr:
return uint64(y)
case float32:
return float64(y)
case complex64:
return complex128(y)
}
panic(fmt.Sprintf("cannot widen %T", x))
}
// conv converts the value x of type t_src to type t_dst and returns
// the result.
// Possible cases are described with the ssa.Convert operator.
func conv(t_dst, t_src types.Type, x value) value {
ut_src := t_src.Underlying()
ut_dst := t_dst.Underlying()
// Destination type is not an "untyped" type.
if b, ok := ut_dst.(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
panic("oops: conversion to 'untyped' type: " + b.String())
}
// Nor is it an interface type.
if _, ok := ut_dst.(*types.Interface); ok {
if _, ok := ut_src.(*types.Interface); ok {
panic("oops: Convert should be ChangeInterface")
} else {
panic("oops: Convert should be MakeInterface")
}
}
// Remaining conversions:
// + untyped string/number/bool constant to a specific
// representation.
// + conversions between non-complex numeric types.
// + conversions between complex numeric types.
// + integer/[]byte/[]rune -> string.
// + string -> []byte/[]rune.
//
// All are treated the same: first we extract the value to the
// widest representation (int64, uint64, float64, complex128,
// or string), then we convert it to the desired type.
switch ut_src := ut_src.(type) {
case *types.Pointer:
switch ut_dst := ut_dst.(type) {
case *types.Basic:
// *value to unsafe.Pointer?
if ut_dst.Kind() == types.UnsafePointer {
return unsafe.Pointer(x.(*value))
}
}
case *types.Slice:
// []byte or []rune -> string
switch ut_src.Elem().Underlying().(*types.Basic).Kind() {
case types.Byte:
x := x.([]value)
b := make([]byte, 0, len(x))
for i := range x {
b = append(b, x[i].(byte))
}
return string(b)
case types.Rune:
x := x.([]value)
r := make([]rune, 0, len(x))
for i := range x {
r = append(r, x[i].(rune))
}
return string(r)
}
case *types.Basic:
x = widen(x)
// integer -> string?
if ut_src.Info()&types.IsInteger != 0 {
if ut_dst, ok := ut_dst.(*types.Basic); ok && ut_dst.Kind() == types.String {
return fmt.Sprintf("%c", x)
}
}
// string -> []rune, []byte or string?
if s, ok := x.(string); ok {
switch ut_dst := ut_dst.(type) {
case *types.Slice:
var res []value
switch ut_dst.Elem().Underlying().(*types.Basic).Kind() {
case types.Rune:
for _, r := range []rune(s) {
res = append(res, r)
}
return res
case types.Byte:
for _, b := range []byte(s) {
res = append(res, b)
}
return res
}
case *types.Basic:
if ut_dst.Kind() == types.String {
return x.(string)
}
}
break // fail: no other conversions for string
}
// unsafe.Pointer -> *value
if ut_src.Kind() == types.UnsafePointer {
// TODO(adonovan): this is wrong and cannot
// really be fixed with the current design.
//
// return (*value)(x.(unsafe.Pointer))
// creates a new pointer of a different
// type but the underlying interface value
// knows its "true" type and so cannot be
// meaningfully used through the new pointer.
//
// To make this work, the interpreter needs to
// simulate the memory layout of a real
// compiled implementation.
//
// To at least preserve type-safety, we'll
// just return the zero value of the
// destination type.
return zero(t_dst)
}
// Conversions between complex numeric types?
if ut_src.Info()&types.IsComplex != 0 {
switch ut_dst.(*types.Basic).Kind() {
case types.Complex64:
return complex64(x.(complex128))
case types.Complex128:
return x.(complex128)
}
break // fail: no other conversions for complex
}
// Conversions between non-complex numeric types?
if ut_src.Info()&types.IsNumeric != 0 {
kind := ut_dst.(*types.Basic).Kind()
switch x := x.(type) {
case int64: // signed integer -> numeric?
switch kind {
case types.Int:
return int(x)
case types.Int8:
return int8(x)
case types.Int16:
return int16(x)
case types.Int32:
return int32(x)
case types.Int64:
return int64(x)
case types.Uint:
return uint(x)
case types.Uint8:
return uint8(x)
case types.Uint16:
return uint16(x)
case types.Uint32:
return uint32(x)
case types.Uint64:
return uint64(x)
case types.Uintptr:
return uintptr(x)
case types.Float32:
return float32(x)
case types.Float64:
return float64(x)
}
case uint64: // unsigned integer -> numeric?
switch kind {
case types.Int:
return int(x)
case types.Int8:
return int8(x)
case types.Int16:
return int16(x)
case types.Int32:
return int32(x)
case types.Int64:
return int64(x)
case types.Uint:
return uint(x)
case types.Uint8:
return uint8(x)
case types.Uint16:
return uint16(x)
case types.Uint32:
return uint32(x)
case types.Uint64:
return uint64(x)
case types.Uintptr:
return uintptr(x)
case types.Float32:
return float32(x)
case types.Float64:
return float64(x)
}
case float64: // floating point -> numeric?
switch kind {
case types.Int:
return int(x)
case types.Int8:
return int8(x)
case types.Int16:
return int16(x)
case types.Int32:
return int32(x)
case types.Int64:
return int64(x)
case types.Uint:
return uint(x)
case types.Uint8:
return uint8(x)
case types.Uint16:
return uint16(x)
case types.Uint32:
return uint32(x)
case types.Uint64:
return uint64(x)
case types.Uintptr:
return uintptr(x)
case types.Float32:
return float32(x)
case types.Float64:
return float64(x)
}
}
}
}
panic(fmt.Sprintf("unsupported conversion: %s -> %s, dynamic type %T", t_src, t_dst, x))
}
// sliceToArrayPointer converts the value x of type slice to type t_dst
// a pointer to array and returns the result.
func sliceToArrayPointer(t_dst, t_src types.Type, x value) value {
if _, ok := t_src.Underlying().(*types.Slice); ok {
if ptr, ok := t_dst.Underlying().(*types.Pointer); ok {
if arr, ok := ptr.Elem().Underlying().(*types.Array); ok {
x := x.([]value)
if arr.Len() > int64(len(x)) {
panic("array length is greater than slice length")
}
if x == nil {
return zero(t_dst)
}
v := value(array(x[:arr.Len()]))
return &v
}
}
}
panic(fmt.Sprintf("unsupported conversion: %s -> %s, dynamic type %T", t_src, t_dst, x))
}
// checkInterface checks that the method set of x implements the
// interface itype.
// On success it returns "", on failure, an error message.
func checkInterface(i *interpreter, itype *types.Interface, x iface) string {
if meth, _ := types.MissingMethod(x.t, itype, true); meth != nil {
return fmt.Sprintf("interface conversion: %v is not %v: missing method %s",
x.t, itype, meth.Name())
}
return "" // ok
}
func foldLeft(op func(value, value) value, args []value) value {
x := args[0]
for _, arg := range args[1:] {
x = op(x, arg)
}
return x
}
func min(x, y value) value {
switch x := x.(type) {
case float32:
return fmin(x, y.(float32))
case float64:
return fmin(x, y.(float64))
}
// return (y < x) ? y : x
if binop(token.LSS, nil, y, x).(bool) {
return y
}
return x
}
func max(x, y value) value {
switch x := x.(type) {
case float32:
return fmax(x, y.(float32))
case float64:
return fmax(x, y.(float64))
}
// return (y > x) ? y : x
if binop(token.GTR, nil, y, x).(bool) {
return y
}
return x
}
// copied from $GOROOT/src/runtime/minmax.go
type floaty interface{ ~float32 | ~float64 }
func fmin[F floaty](x, y F) F {
if y != y || y < x {
return y
}
if x != x || x < y || x != 0 {
return x
}
// x and y are both ±0
// if either is -0, return -0; else return +0
return forbits(x, y)
}
func fmax[F floaty](x, y F) F {
if y != y || y > x {
return y
}
if x != x || x > y || x != 0 {
return x
}
// x and y are both ±0
// if both are -0, return -0; else return +0
return fandbits(x, y)
}
func forbits[F floaty](x, y F) F {
switch unsafe.Sizeof(x) {
case 4:
*(*uint32)(unsafe.Pointer(&x)) |= *(*uint32)(unsafe.Pointer(&y))
case 8:
*(*uint64)(unsafe.Pointer(&x)) |= *(*uint64)(unsafe.Pointer(&y))
}
return x
}
func fandbits[F floaty](x, y F) F {
switch unsafe.Sizeof(x) {
case 4:
*(*uint32)(unsafe.Pointer(&x)) &= *(*uint32)(unsafe.Pointer(&y))
case 8:
*(*uint64)(unsafe.Pointer(&x)) &= *(*uint64)(unsafe.Pointer(&y))
}
return x
}
| tools/go/ssa/interp/ops.go/0 | {
"file_path": "tools/go/ssa/interp/ops.go",
"repo_id": "tools",
"token_count": 15236
} | 710 |
package main
// Tests of interface conversions and type assertions.
type I0 interface {
}
type I1 interface {
f()
}
type I2 interface {
f()
g()
}
type C0 struct{}
type C1 struct{}
func (C1) f() {}
type C2 struct{}
func (C2) f() {}
func (C2) g() {}
func main() {
var i0 I0
var i1 I1
var i2 I2
// Nil always causes a type assertion to fail, even to the
// same type.
if _, ok := i0.(I0); ok {
panic("nil i0.(I0) succeeded")
}
if _, ok := i1.(I1); ok {
panic("nil i1.(I1) succeeded")
}
if _, ok := i2.(I2); ok {
panic("nil i2.(I2) succeeded")
}
// Conversions can't fail, even with nil.
_ = I0(i0)
_ = I0(i1)
_ = I1(i1)
_ = I0(i2)
_ = I1(i2)
_ = I2(i2)
// Non-nil type assertions pass or fail based on the concrete type.
i1 = C1{}
if _, ok := i1.(I0); !ok {
panic("C1 i1.(I0) failed")
}
if _, ok := i1.(I1); !ok {
panic("C1 i1.(I1) failed")
}
if _, ok := i1.(I2); ok {
panic("C1 i1.(I2) succeeded")
}
i1 = C2{}
if _, ok := i1.(I0); !ok {
panic("C2 i1.(I0) failed")
}
if _, ok := i1.(I1); !ok {
panic("C2 i1.(I1) failed")
}
if _, ok := i1.(I2); !ok {
panic("C2 i1.(I2) failed")
}
// Conversions can't fail.
i1 = C1{}
if I0(i1) == nil {
panic("C1 I0(i1) was nil")
}
if I1(i1) == nil {
panic("C1 I1(i1) was nil")
}
}
| tools/go/ssa/interp/testdata/ifaceconv.go/0 | {
"file_path": "tools/go/ssa/interp/testdata/ifaceconv.go",
"repo_id": "tools",
"token_count": 640
} | 711 |
package errors
func New(text string) error { return errorString{text} }
type errorString struct{ s string }
func (e errorString) Error() string { return e.s }
| tools/go/ssa/interp/testdata/src/errors/errors.go/0 | {
"file_path": "tools/go/ssa/interp/testdata/src/errors/errors.go",
"repo_id": "tools",
"token_count": 47
} | 712 |
package main
// Static tests of SSA builder (via the sanity checker).
// Dynamic semantics are not exercised.
func init() {
// Regression test for issue 6806.
ch := make(chan int)
select {
case n, _ := <-ch:
_ = n
default:
// The default case disables the simplification of
// select to a simple receive statement.
}
// value,ok-form receive where TypeOf(ok) is a named boolean.
type mybool bool
var x int
var y mybool
select {
case x, y = <-ch:
default:
// The default case disables the simplification of
// select to a simple receive statement.
}
_ = x
_ = y
}
var a int
// Regression test for issue 7840 (covered by SSA sanity checker).
func bug7840() bool {
// This creates a single-predecessor block with a φ-node.
return false && a == 0 && a == 0
}
// A blocking select (sans "default:") cannot fall through.
// Regression test for issue 7022.
func bug7022() int {
var c1, c2 chan int
select {
case <-c1:
return 123
case <-c2:
return 456
}
}
// Parens should not prevent intrinsic treatment of built-ins.
// (Regression test for a crash.)
func init() {
_ = (new)(int)
_ = (make)([]int, 0)
}
func main() {}
| tools/go/ssa/interp/testdata/static.go/0 | {
"file_path": "tools/go/ssa/interp/testdata/static.go",
"repo_id": "tools",
"token_count": 403
} | 713 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ssautil_test
import (
"bytes"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
"os"
"path"
"strings"
"testing"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/packages/packagestest"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/ssautil"
"golang.org/x/tools/internal/testenv"
)
const hello = `package main
import "fmt"
func main() {
fmt.Println("Hello, world")
}
`
func TestBuildPackage(t *testing.T) {
testenv.NeedsGoBuild(t) // for importer.Default()
// There is a more substantial test of BuildPackage and the
// SSA program it builds in ../ssa/builder_test.go.
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "hello.go", hello, 0)
if err != nil {
t.Fatal(err)
}
for _, mode := range []ssa.BuilderMode{
ssa.SanityCheckFunctions,
ssa.InstantiateGenerics | ssa.SanityCheckFunctions,
} {
pkg := types.NewPackage("hello", "")
ssapkg, _, err := ssautil.BuildPackage(&types.Config{Importer: importer.Default()}, fset, pkg, []*ast.File{f}, mode)
if err != nil {
t.Fatal(err)
}
if pkg.Name() != "main" {
t.Errorf("pkg.Name() = %s, want main", pkg.Name())
}
if ssapkg.Func("main") == nil {
ssapkg.WriteTo(os.Stderr)
t.Errorf("ssapkg has no main function")
}
}
}
func TestPackages(t *testing.T) {
testenv.NeedsGoPackages(t)
cfg := &packages.Config{Mode: packages.LoadSyntax}
initial, err := packages.Load(cfg, "bytes")
if err != nil {
t.Fatal(err)
}
if packages.PrintErrors(initial) > 0 {
t.Fatal("there were errors")
}
for _, mode := range []ssa.BuilderMode{
ssa.SanityCheckFunctions,
ssa.SanityCheckFunctions | ssa.InstantiateGenerics,
} {
prog, pkgs := ssautil.Packages(initial, mode)
bytesNewBuffer := pkgs[0].Func("NewBuffer")
bytesNewBuffer.Pkg.Build()
// We'll dump the SSA of bytes.NewBuffer because it is small and stable.
out := new(bytes.Buffer)
bytesNewBuffer.WriteTo(out)
// For determinism, sanitize the location.
location := prog.Fset.Position(bytesNewBuffer.Pos()).String()
got := strings.Replace(out.String(), location, "$GOROOT/src/bytes/buffer.go:1", -1)
want := `
# Name: bytes.NewBuffer
# Package: bytes
# Location: $GOROOT/src/bytes/buffer.go:1
func NewBuffer(buf []byte) *Buffer:
0: entry P:0 S:0
t0 = new Buffer (complit) *Buffer
t1 = &t0.buf [#0] *[]byte
*t1 = buf
return t0
`[1:]
if got != want {
t.Errorf("bytes.NewBuffer SSA = <<%s>>, want <<%s>>", got, want)
}
}
}
func TestBuildPackage_MissingImport(t *testing.T) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "bad.go", `package bad; import "missing"`, 0)
if err != nil {
t.Fatal(err)
}
pkg := types.NewPackage("bad", "")
ssapkg, _, err := ssautil.BuildPackage(new(types.Config), fset, pkg, []*ast.File{f}, ssa.BuilderMode(0))
if err == nil || ssapkg != nil {
t.Fatal("BuildPackage succeeded unexpectedly")
}
}
func TestIssue28106(t *testing.T) {
testenv.NeedsGoPackages(t)
// In go1.10, go/packages loads all packages from source, not
// export data, but does not type check function bodies of
// imported packages. This test ensures that we do not attempt
// to run the SSA builder on functions without type information.
cfg := &packages.Config{Mode: packages.LoadSyntax}
pkgs, err := packages.Load(cfg, "runtime")
if err != nil {
t.Fatal(err)
}
prog, _ := ssautil.Packages(pkgs, ssa.BuilderMode(0))
prog.Build() // no crash
}
func TestIssue53604(t *testing.T) {
// Tests that variable initializers are not added to init() when syntax
// is not present but types.Info is available.
//
// Packages x, y, z are loaded with mode `packages.LoadSyntax`.
// Package x imports y, and y imports z.
// Packages are built using ssautil.Packages() with x and z as roots.
// This setup creates y using CreatePackage(pkg, files, info, ...)
// where len(files) == 0 but info != nil.
//
// Tests that globals from y are not initialized.
e := packagestest.Export(t, packagestest.Modules, []packagestest.Module{
{
Name: "golang.org/fake",
Files: map[string]interface{}{
"x/x.go": `package x; import "golang.org/fake/y"; var V = y.F()`,
"y/y.go": `package y; import "golang.org/fake/z"; var F = func () *int { return &z.Z } `,
"z/z.go": `package z; var Z int`,
},
},
})
defer e.Cleanup()
// Load x and z as entry packages using packages.LoadSyntax
e.Config.Mode = packages.LoadSyntax
pkgs, err := packages.Load(e.Config, path.Join(e.Temp(), "fake/x"), path.Join(e.Temp(), "fake/z"))
if err != nil {
t.Fatal(err)
}
for _, p := range pkgs {
if len(p.Errors) > 0 {
t.Fatalf("%v", p.Errors)
}
}
prog, _ := ssautil.Packages(pkgs, ssa.BuilderMode(0))
prog.Build()
// y does not initialize F.
y := prog.ImportedPackage("golang.org/fake/y")
if y == nil {
t.Fatal("Failed to load intermediate package y")
}
yinit := y.Members["init"].(*ssa.Function)
for _, bb := range yinit.Blocks {
for _, i := range bb.Instrs {
if store, ok := i.(*ssa.Store); ok && store.Addr == y.Var("F") {
t.Errorf("y.init() stores to F %v", store)
}
}
}
}
| tools/go/ssa/ssautil/load_test.go/0 | {
"file_path": "tools/go/ssa/ssautil/load_test.go",
"repo_id": "tools",
"token_count": 2263
} | 714 |
package encoding
type BinaryMarshaler interface {
MarshalBinary() (data []byte, err error)
}
type BinaryUnmarshaler interface {
UnmarshalBinary(data []byte) error
}
| tools/go/ssa/testdata/src/encoding/encoding.go/0 | {
"file_path": "tools/go/ssa/testdata/src/encoding/encoding.go",
"repo_id": "tools",
"token_count": 54
} | 715 |
package time
type Duration int64
func Sleep(Duration)
func NewTimer(d Duration) *Timer
type Timer struct {
C <-chan Time
}
func (t *Timer) Stop() bool
type Time struct{}
func After(d Duration) <-chan Time
const (
Nanosecond Duration = iota // Specific values do not matter here.
Second
Minute
Hour
)
| tools/go/ssa/testdata/src/time/time.go/0 | {
"file_path": "tools/go/ssa/testdata/src/time/time.go",
"repo_id": "tools",
"token_count": 105
} | 716 |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package typeutil_test
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"testing"
"golang.org/x/tools/go/types/typeutil"
)
type closure map[string]*types.Package
func (c closure) Import(path string) (*types.Package, error) { return c[path], nil }
func TestDependencies(t *testing.T) {
packages := make(map[string]*types.Package)
conf := types.Config{
Importer: closure(packages),
}
fset := token.NewFileSet()
// All edges go to the right.
// /--D--B--A
// F \_C_/
// \__E_/
for i, content := range []string{
`package a`,
`package c; import (_ "a")`,
`package b; import (_ "a")`,
`package e; import (_ "c")`,
`package d; import (_ "b"; _ "c")`,
`package f; import (_ "d"; _ "e")`,
} {
f, err := parser.ParseFile(fset, fmt.Sprintf("%d.go", i), content, 0)
if err != nil {
t.Fatal(err)
}
pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil)
if err != nil {
t.Fatal(err)
}
packages[pkg.Path()] = pkg
}
for _, test := range []struct {
roots, want string
}{
{"a", "a"},
{"b", "ab"},
{"c", "ac"},
{"d", "abcd"},
{"e", "ace"},
{"f", "abcdef"},
{"be", "abce"},
{"eb", "aceb"},
{"de", "abcde"},
{"ed", "acebd"},
{"ef", "acebdf"},
} {
var pkgs []*types.Package
for _, r := range test.roots {
pkgs = append(pkgs, packages[string(r)])
}
var got string
for _, p := range typeutil.Dependencies(pkgs...) {
got += p.Path()
}
if got != test.want {
t.Errorf("Dependencies(%q) = %q, want %q", test.roots, got, test.want)
}
}
}
| tools/go/types/typeutil/imports_test.go/0 | {
"file_path": "tools/go/types/typeutil/imports_test.go",
"repo_id": "tools",
"token_count": 747
} | 717 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file contains the infrastructure to create an
// identifier and full-text index for a set of Go files.
//
// Algorithm for identifier index:
// - traverse all .go files of the file tree specified by root
// - for each identifier (word) encountered, collect all occurrences (spots)
// into a list; this produces a list of spots for each word
// - reduce the lists: from a list of spots to a list of FileRuns,
// and from a list of FileRuns into a list of PakRuns
// - make a HitList from the PakRuns
//
// Details:
// - keep two lists per word: one containing package-level declarations
// that have snippets, and one containing all other spots
// - keep the snippets in a separate table indexed by snippet index
// and store the snippet index in place of the line number in a SpotInfo
// (the line number for spots with snippets is stored in the snippet)
// - at the end, create lists of alternative spellings for a given
// word
//
// Algorithm for full text index:
// - concatenate all source code in a byte buffer (in memory)
// - add the files to a file set in lockstep as they are added to the byte
// buffer such that a byte buffer offset corresponds to the Pos value for
// that file location
// - create a suffix array from the concatenated sources
//
// String lookup in full text index:
// - use the suffix array to lookup a string's offsets - the offsets
// correspond to the Pos values relative to the file set
// - translate the Pos values back into file and line information and
// sort the result
package godoc
import (
"bufio"
"bytes"
"encoding/gob"
"errors"
"fmt"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"index/suffixarray"
"io"
"log"
"math"
"os"
pathpkg "path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"golang.org/x/tools/godoc/util"
"golang.org/x/tools/godoc/vfs"
)
// ----------------------------------------------------------------------------
// InterfaceSlice is a helper type for sorting interface
// slices according to some slice-specific sort criteria.
type comparer func(x, y interface{}) bool
type interfaceSlice struct {
slice []interface{}
less comparer
}
// ----------------------------------------------------------------------------
// RunList
// A RunList is a list of entries that can be sorted according to some
// criteria. A RunList may be compressed by grouping "runs" of entries
// which are equal (according to the sort criteria) into a new RunList of
// runs. For instance, a RunList containing pairs (x, y) may be compressed
// into a RunList containing pair runs (x, {y}) where each run consists of
// a list of y's with the same x.
type RunList []interface{}
func (h RunList) sort(less comparer) {
sort.Sort(&interfaceSlice{h, less})
}
func (p *interfaceSlice) Len() int { return len(p.slice) }
func (p *interfaceSlice) Less(i, j int) bool { return p.less(p.slice[i], p.slice[j]) }
func (p *interfaceSlice) Swap(i, j int) { p.slice[i], p.slice[j] = p.slice[j], p.slice[i] }
// Compress entries which are the same according to a sort criteria
// (specified by less) into "runs".
func (h RunList) reduce(less comparer, newRun func(h RunList) interface{}) RunList {
if len(h) == 0 {
return nil
}
// len(h) > 0
// create runs of entries with equal values
h.sort(less)
// for each run, make a new run object and collect them in a new RunList
var hh RunList
i, x := 0, h[0]
for j, y := range h {
if less(x, y) {
hh = append(hh, newRun(h[i:j]))
i, x = j, h[j] // start a new run
}
}
// add final run, if any
if i < len(h) {
hh = append(hh, newRun(h[i:]))
}
return hh
}
// ----------------------------------------------------------------------------
// KindRun
// Debugging support. Disable to see multiple entries per line.
const removeDuplicates = true
// A KindRun is a run of SpotInfos of the same kind in a given file.
// The kind (3 bits) is stored in each SpotInfo element; to find the
// kind of a KindRun, look at any of its elements.
type KindRun []SpotInfo
// KindRuns are sorted by line number or index. Since the isIndex bit
// is always the same for all infos in one list we can compare lori's.
func (k KindRun) Len() int { return len(k) }
func (k KindRun) Less(i, j int) bool { return k[i].Lori() < k[j].Lori() }
func (k KindRun) Swap(i, j int) { k[i], k[j] = k[j], k[i] }
// FileRun contents are sorted by Kind for the reduction into KindRuns.
func lessKind(x, y interface{}) bool { return x.(SpotInfo).Kind() < y.(SpotInfo).Kind() }
// newKindRun allocates a new KindRun from the SpotInfo run h.
func newKindRun(h RunList) interface{} {
run := make(KindRun, len(h))
for i, x := range h {
run[i] = x.(SpotInfo)
}
// Spots were sorted by file and kind to create this run.
// Within this run, sort them by line number or index.
sort.Sort(run)
if removeDuplicates {
// Since both the lori and kind field must be
// same for duplicates, and since the isIndex
// bit is always the same for all infos in one
// list we can simply compare the entire info.
k := 0
prev := SpotInfo(math.MaxUint32) // an unlikely value
for _, x := range run {
if x != prev {
run[k] = x
k++
prev = x
}
}
run = run[0:k]
}
return run
}
// ----------------------------------------------------------------------------
// FileRun
// A Pak describes a Go package.
type Pak struct {
Path string // path of directory containing the package
Name string // package name as declared by package clause
}
// Paks are sorted by name (primary key) and by import path (secondary key).
func (p *Pak) less(q *Pak) bool {
return p.Name < q.Name || p.Name == q.Name && p.Path < q.Path
}
// A File describes a Go file.
type File struct {
Name string // directory-local file name
Pak *Pak // the package to which the file belongs
}
// Path returns the file path of f.
func (f *File) Path() string {
return pathpkg.Join(f.Pak.Path, f.Name)
}
// A Spot describes a single occurrence of a word.
type Spot struct {
File *File
Info SpotInfo
}
// A FileRun is a list of KindRuns belonging to the same file.
type FileRun struct {
File *File
Groups []KindRun
}
// Spots are sorted by file path for the reduction into FileRuns.
func lessSpot(x, y interface{}) bool {
fx := x.(Spot).File
fy := y.(Spot).File
// same as "return fx.Path() < fy.Path()" but w/o computing the file path first
px := fx.Pak.Path
py := fy.Pak.Path
return px < py || px == py && fx.Name < fy.Name
}
// newFileRun allocates a new FileRun from the Spot run h.
func newFileRun(h RunList) interface{} {
file := h[0].(Spot).File
// reduce the list of Spots into a list of KindRuns
h1 := make(RunList, len(h))
for i, x := range h {
h1[i] = x.(Spot).Info
}
h2 := h1.reduce(lessKind, newKindRun)
// create the FileRun
groups := make([]KindRun, len(h2))
for i, x := range h2 {
groups[i] = x.(KindRun)
}
return &FileRun{file, groups}
}
// ----------------------------------------------------------------------------
// PakRun
// A PakRun describes a run of *FileRuns of a package.
type PakRun struct {
Pak *Pak
Files []*FileRun
}
// Sorting support for files within a PakRun.
func (p *PakRun) Len() int { return len(p.Files) }
func (p *PakRun) Less(i, j int) bool { return p.Files[i].File.Name < p.Files[j].File.Name }
func (p *PakRun) Swap(i, j int) { p.Files[i], p.Files[j] = p.Files[j], p.Files[i] }
// FileRuns are sorted by package for the reduction into PakRuns.
func lessFileRun(x, y interface{}) bool {
return x.(*FileRun).File.Pak.less(y.(*FileRun).File.Pak)
}
// newPakRun allocates a new PakRun from the *FileRun run h.
func newPakRun(h RunList) interface{} {
pak := h[0].(*FileRun).File.Pak
files := make([]*FileRun, len(h))
for i, x := range h {
files[i] = x.(*FileRun)
}
run := &PakRun{pak, files}
sort.Sort(run) // files were sorted by package; sort them by file now
return run
}
// ----------------------------------------------------------------------------
// HitList
// A HitList describes a list of PakRuns.
type HitList []*PakRun
// PakRuns are sorted by package.
func lessPakRun(x, y interface{}) bool { return x.(*PakRun).Pak.less(y.(*PakRun).Pak) }
func reduce(h0 RunList) HitList {
// reduce a list of Spots into a list of FileRuns
h1 := h0.reduce(lessSpot, newFileRun)
// reduce a list of FileRuns into a list of PakRuns
h2 := h1.reduce(lessFileRun, newPakRun)
// sort the list of PakRuns by package
h2.sort(lessPakRun)
// create a HitList
h := make(HitList, len(h2))
for i, p := range h2 {
h[i] = p.(*PakRun)
}
return h
}
// filter returns a new HitList created by filtering
// all PakRuns from h that have a matching pakname.
func (h HitList) filter(pakname string) HitList {
var hh HitList
for _, p := range h {
if p.Pak.Name == pakname {
hh = append(hh, p)
}
}
return hh
}
// ----------------------------------------------------------------------------
// AltWords
type wordPair struct {
canon string // canonical word spelling (all lowercase)
alt string // alternative spelling
}
// An AltWords describes a list of alternative spellings for a
// canonical (all lowercase) spelling of a word.
type AltWords struct {
Canon string // canonical word spelling (all lowercase)
Alts []string // alternative spelling for the same word
}
// wordPairs are sorted by their canonical spelling.
func lessWordPair(x, y interface{}) bool { return x.(*wordPair).canon < y.(*wordPair).canon }
// newAltWords allocates a new AltWords from the *wordPair run h.
func newAltWords(h RunList) interface{} {
canon := h[0].(*wordPair).canon
alts := make([]string, len(h))
for i, x := range h {
alts[i] = x.(*wordPair).alt
}
return &AltWords{canon, alts}
}
func (a *AltWords) filter(s string) *AltWords {
var alts []string
for _, w := range a.Alts {
if w != s {
alts = append(alts, w)
}
}
if len(alts) > 0 {
return &AltWords{a.Canon, alts}
}
return nil
}
// Ident stores information about external identifiers in order to create
// links to package documentation.
type Ident struct {
Path string // e.g. "net/http"
Package string // e.g. "http"
Name string // e.g. "NewRequest"
Doc string // e.g. "NewRequest returns a new Request..."
}
// byImportCount sorts the given slice of Idents by the import
// counts of the packages to which they belong.
type byImportCount struct {
Idents []Ident
ImportCount map[string]int
}
func (ic byImportCount) Len() int {
return len(ic.Idents)
}
func (ic byImportCount) Less(i, j int) bool {
ri := ic.ImportCount[ic.Idents[i].Path]
rj := ic.ImportCount[ic.Idents[j].Path]
if ri == rj {
return ic.Idents[i].Path < ic.Idents[j].Path
}
return ri > rj
}
func (ic byImportCount) Swap(i, j int) {
ic.Idents[i], ic.Idents[j] = ic.Idents[j], ic.Idents[i]
}
func (ic byImportCount) String() string {
buf := bytes.NewBuffer([]byte("["))
for _, v := range ic.Idents {
buf.WriteString(fmt.Sprintf("\n\t%s, %s (%d)", v.Path, v.Name, ic.ImportCount[v.Path]))
}
buf.WriteString("\n]")
return buf.String()
}
// filter creates a new Ident list where the results match the given
// package name.
func (ic byImportCount) filter(pakname string) []Ident {
if ic.Idents == nil {
return nil
}
var res []Ident
for _, i := range ic.Idents {
if i.Package == pakname {
res = append(res, i)
}
}
return res
}
// top returns the top n identifiers.
func (ic byImportCount) top(n int) []Ident {
if len(ic.Idents) > n {
return ic.Idents[:n]
}
return ic.Idents
}
// ----------------------------------------------------------------------------
// Indexer
type IndexResult struct {
Decls RunList // package-level declarations (with snippets)
Others RunList // all other occurrences
}
// Statistics provides statistics information for an index.
type Statistics struct {
Bytes int // total size of indexed source files
Files int // number of indexed source files
Lines int // number of lines (all files)
Words int // number of different identifiers
Spots int // number of identifier occurrences
}
// An Indexer maintains the data structures and provides the machinery
// for indexing .go files under a file tree. It implements the path.Visitor
// interface for walking file trees, and the ast.Visitor interface for
// walking Go ASTs.
type Indexer struct {
c *Corpus
fset *token.FileSet // file set for all indexed files
fsOpenGate chan bool // send pre fs.Open; receive on close
mu sync.Mutex // guards all the following
sources bytes.Buffer // concatenated sources
strings map[string]string // interned string
packages map[Pak]*Pak // interned *Paks
words map[string]*IndexResult // RunLists of Spots
snippets []*Snippet // indices are stored in SpotInfos
current *token.File // last file added to file set
file *File // AST for current file
decl ast.Decl // AST for current decl
stats Statistics
throttle *util.Throttle
importCount map[string]int // package path ("net/http") => count
packagePath map[string]map[string]bool // "template" => "text/template" => true
exports map[string]map[string]SpotKind // "net/http" => "ListenAndServe" => FuncDecl
curPkgExports map[string]SpotKind
idents map[SpotKind]map[string][]Ident // kind => name => list of Idents
}
func (x *Indexer) intern(s string) string {
if s, ok := x.strings[s]; ok {
return s
}
x.strings[s] = s
return s
}
func (x *Indexer) lookupPackage(path, name string) *Pak {
// In the source directory tree, more than one package may
// live in the same directory. For the packages map, construct
// a key that includes both the directory path and the package
// name.
key := Pak{Path: x.intern(path), Name: x.intern(name)}
pak := x.packages[key]
if pak == nil {
pak = &key
x.packages[key] = pak
}
return pak
}
func (x *Indexer) addSnippet(s *Snippet) int {
index := len(x.snippets)
x.snippets = append(x.snippets, s)
return index
}
func (x *Indexer) visitIdent(kind SpotKind, id *ast.Ident) {
if id == nil {
return
}
name := x.intern(id.Name)
switch kind {
case TypeDecl, FuncDecl, ConstDecl, VarDecl:
x.curPkgExports[name] = kind
}
lists, found := x.words[name]
if !found {
lists = new(IndexResult)
x.words[name] = lists
}
if kind == Use || x.decl == nil {
if x.c.IndexGoCode {
// not a declaration or no snippet required
info := makeSpotInfo(kind, x.current.Line(id.Pos()), false)
lists.Others = append(lists.Others, Spot{x.file, info})
}
} else {
// a declaration with snippet
index := x.addSnippet(NewSnippet(x.fset, x.decl, id))
info := makeSpotInfo(kind, index, true)
lists.Decls = append(lists.Decls, Spot{x.file, info})
}
x.stats.Spots++
}
func (x *Indexer) visitFieldList(kind SpotKind, flist *ast.FieldList) {
for _, f := range flist.List {
x.decl = nil // no snippets for fields
for _, name := range f.Names {
x.visitIdent(kind, name)
}
ast.Walk(x, f.Type)
// ignore tag - not indexed at the moment
}
}
func (x *Indexer) visitSpec(kind SpotKind, spec ast.Spec) {
switch n := spec.(type) {
case *ast.ImportSpec:
x.visitIdent(ImportDecl, n.Name)
if n.Path != nil {
if imp, err := strconv.Unquote(n.Path.Value); err == nil {
x.importCount[x.intern(imp)]++
}
}
case *ast.ValueSpec:
for _, n := range n.Names {
x.visitIdent(kind, n)
}
ast.Walk(x, n.Type)
for _, v := range n.Values {
ast.Walk(x, v)
}
case *ast.TypeSpec:
x.visitIdent(TypeDecl, n.Name)
ast.Walk(x, n.Type)
}
}
func (x *Indexer) visitGenDecl(decl *ast.GenDecl) {
kind := VarDecl
if decl.Tok == token.CONST {
kind = ConstDecl
}
x.decl = decl
for _, s := range decl.Specs {
x.visitSpec(kind, s)
}
}
func (x *Indexer) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {
case nil:
// nothing to do
case *ast.Ident:
x.visitIdent(Use, n)
case *ast.FieldList:
x.visitFieldList(VarDecl, n)
case *ast.InterfaceType:
x.visitFieldList(MethodDecl, n.Methods)
case *ast.DeclStmt:
// local declarations should only be *ast.GenDecls;
// ignore incorrect ASTs
if decl, ok := n.Decl.(*ast.GenDecl); ok {
x.decl = nil // no snippets for local declarations
x.visitGenDecl(decl)
}
case *ast.GenDecl:
x.decl = n
x.visitGenDecl(n)
case *ast.FuncDecl:
kind := FuncDecl
if n.Recv != nil {
kind = MethodDecl
ast.Walk(x, n.Recv)
}
x.decl = n
x.visitIdent(kind, n.Name)
ast.Walk(x, n.Type)
if n.Body != nil {
ast.Walk(x, n.Body)
}
case *ast.File:
x.decl = nil
x.visitIdent(PackageClause, n.Name)
for _, d := range n.Decls {
ast.Walk(x, d)
}
default:
return x
}
return nil
}
// addFile adds a file to the index if possible and returns the file set file
// and the file's AST if it was successfully parsed as a Go file. If addFile
// failed (that is, if the file was not added), it returns file == nil.
func (x *Indexer) addFile(f vfs.ReadSeekCloser, filename string, goFile bool) (file *token.File, ast *ast.File) {
defer f.Close()
// The file set's base offset and x.sources size must be in lock-step;
// this permits the direct mapping of suffix array lookup results to
// corresponding Pos values.
//
// When a file is added to the file set, its offset base increases by
// the size of the file + 1; and the initial base offset is 1. Add an
// extra byte to the sources here.
x.sources.WriteByte(0)
// If the sources length doesn't match the file set base at this point
// the file set implementation changed or we have another error.
base := x.fset.Base()
if x.sources.Len() != base {
panic("internal error: file base incorrect")
}
// append file contents (src) to x.sources
if _, err := x.sources.ReadFrom(f); err == nil {
src := x.sources.Bytes()[base:]
if goFile {
// parse the file and in the process add it to the file set
if ast, err = parser.ParseFile(x.fset, filename, src, parser.ParseComments); err == nil {
file = x.fset.File(ast.Pos()) // ast.Pos() is inside the file
return
}
// file has parse errors, and the AST may be incorrect -
// set lines information explicitly and index as ordinary
// text file (cannot fall through to the text case below
// because the file has already been added to the file set
// by the parser)
file = x.fset.File(token.Pos(base)) // token.Pos(base) is inside the file
file.SetLinesForContent(src)
ast = nil
return
}
if util.IsText(src) {
// only add the file to the file set (for the full text index)
file = x.fset.AddFile(filename, x.fset.Base(), len(src))
file.SetLinesForContent(src)
return
}
}
// discard possibly added data
x.sources.Truncate(base - 1) // -1 to remove added byte 0 since no file was added
return
}
// Design note: Using an explicit white list of permitted files for indexing
// makes sure that the important files are included and massively reduces the
// number of files to index. The advantage over a blacklist is that unexpected
// (non-blacklisted) files won't suddenly explode the index.
// Files are whitelisted if they have a file name or extension
// present as key in whitelisted.
var whitelisted = map[string]bool{
".bash": true,
".c": true,
".cc": true,
".cpp": true,
".cxx": true,
".css": true,
".go": true,
".goc": true,
".h": true,
".hh": true,
".hpp": true,
".hxx": true,
".html": true,
".js": true,
".out": true,
".py": true,
".s": true,
".sh": true,
".txt": true,
".xml": true,
"AUTHORS": true,
"CONTRIBUTORS": true,
"LICENSE": true,
"Makefile": true,
"PATENTS": true,
"README": true,
}
// isWhitelisted returns true if a file is on the list
// of "permitted" files for indexing. The filename must
// be the directory-local name of the file.
func isWhitelisted(filename string) bool {
key := pathpkg.Ext(filename)
if key == "" {
// file has no extension - use entire filename
key = filename
}
return whitelisted[key]
}
func (x *Indexer) indexDocs(dirname string, filename string, astFile *ast.File) {
pkgName := x.intern(astFile.Name.Name)
if pkgName == "main" {
return
}
pkgPath := x.intern(strings.TrimPrefix(strings.TrimPrefix(dirname, "/src/"), "pkg/"))
astPkg := ast.Package{
Name: pkgName,
Files: map[string]*ast.File{
filename: astFile,
},
}
var m doc.Mode
docPkg := doc.New(&astPkg, dirname, m)
addIdent := func(sk SpotKind, name string, docstr string) {
if x.idents[sk] == nil {
x.idents[sk] = make(map[string][]Ident)
}
name = x.intern(name)
x.idents[sk][name] = append(x.idents[sk][name], Ident{
Path: pkgPath,
Package: pkgName,
Name: name,
Doc: doc.Synopsis(docstr),
})
}
if x.idents[PackageClause] == nil {
x.idents[PackageClause] = make(map[string][]Ident)
}
// List of words under which the package identifier will be stored.
// This includes the package name and the components of the directory
// in which it resides.
words := strings.Split(pathpkg.Dir(pkgPath), "/")
if words[0] == "." {
words = []string{}
}
name := x.intern(docPkg.Name)
synopsis := doc.Synopsis(docPkg.Doc)
words = append(words, name)
pkgIdent := Ident{
Path: pkgPath,
Package: pkgName,
Name: name,
Doc: synopsis,
}
for _, word := range words {
word = x.intern(word)
found := false
pkgs := x.idents[PackageClause][word]
for i, p := range pkgs {
if p.Path == pkgPath {
if docPkg.Doc != "" {
p.Doc = synopsis
pkgs[i] = p
}
found = true
break
}
}
if !found {
x.idents[PackageClause][word] = append(x.idents[PackageClause][word], pkgIdent)
}
}
for _, c := range docPkg.Consts {
for _, name := range c.Names {
addIdent(ConstDecl, name, c.Doc)
}
}
for _, t := range docPkg.Types {
addIdent(TypeDecl, t.Name, t.Doc)
for _, c := range t.Consts {
for _, name := range c.Names {
addIdent(ConstDecl, name, c.Doc)
}
}
for _, v := range t.Vars {
for _, name := range v.Names {
addIdent(VarDecl, name, v.Doc)
}
}
for _, f := range t.Funcs {
addIdent(FuncDecl, f.Name, f.Doc)
}
for _, f := range t.Methods {
addIdent(MethodDecl, f.Name, f.Doc)
// Change the name of methods to be "<typename>.<methodname>".
// They will still be indexed as <methodname>.
idents := x.idents[MethodDecl][f.Name]
idents[len(idents)-1].Name = x.intern(t.Name + "." + f.Name)
}
}
for _, v := range docPkg.Vars {
for _, name := range v.Names {
addIdent(VarDecl, name, v.Doc)
}
}
for _, f := range docPkg.Funcs {
addIdent(FuncDecl, f.Name, f.Doc)
}
}
func (x *Indexer) indexGoFile(dirname string, filename string, file *token.File, astFile *ast.File) {
pkgName := astFile.Name.Name
if x.c.IndexGoCode {
x.current = file
pak := x.lookupPackage(dirname, pkgName)
x.file = &File{filename, pak}
ast.Walk(x, astFile)
}
if x.c.IndexDocs {
// Test files are already filtered out in visitFile if IndexGoCode and
// IndexFullText are false. Otherwise, check here.
isTestFile := (x.c.IndexGoCode || x.c.IndexFullText) &&
(strings.HasSuffix(filename, "_test.go") || strings.HasPrefix(dirname, "/test/"))
if !isTestFile {
x.indexDocs(dirname, filename, astFile)
}
}
ppKey := x.intern(pkgName)
if _, ok := x.packagePath[ppKey]; !ok {
x.packagePath[ppKey] = make(map[string]bool)
}
pkgPath := x.intern(strings.TrimPrefix(strings.TrimPrefix(dirname, "/src/"), "pkg/"))
x.packagePath[ppKey][pkgPath] = true
// Merge in exported symbols found walking this file into
// the map for that package.
if len(x.curPkgExports) > 0 {
dest, ok := x.exports[pkgPath]
if !ok {
dest = make(map[string]SpotKind)
x.exports[pkgPath] = dest
}
for k, v := range x.curPkgExports {
dest[k] = v
}
}
}
func (x *Indexer) visitFile(dirname string, fi os.FileInfo) {
if fi.IsDir() || !x.c.IndexEnabled {
return
}
filename := pathpkg.Join(dirname, fi.Name())
goFile := isGoFile(fi)
switch {
case x.c.IndexFullText:
if !isWhitelisted(fi.Name()) {
return
}
case x.c.IndexGoCode:
if !goFile {
return
}
case x.c.IndexDocs:
if !goFile ||
strings.HasSuffix(fi.Name(), "_test.go") ||
strings.HasPrefix(dirname, "/test/") {
return
}
default:
// No indexing turned on.
return
}
x.fsOpenGate <- true
defer func() { <-x.fsOpenGate }()
// open file
f, err := x.c.fs.Open(filename)
if err != nil {
return
}
x.mu.Lock()
defer x.mu.Unlock()
x.throttle.Throttle()
x.curPkgExports = make(map[string]SpotKind)
file, fast := x.addFile(f, filename, goFile)
if file == nil {
return // addFile failed
}
if fast != nil {
x.indexGoFile(dirname, fi.Name(), file, fast)
}
// update statistics
x.stats.Bytes += file.Size()
x.stats.Files++
x.stats.Lines += file.LineCount()
}
// indexOptions contains information that affects the contents of an index.
type indexOptions struct {
// Docs provides documentation search results.
// It is only consulted if IndexEnabled is true.
// The default values is true.
Docs bool
// GoCode provides Go source code search results.
// It is only consulted if IndexEnabled is true.
// The default values is true.
GoCode bool
// FullText provides search results from all files.
// It is only consulted if IndexEnabled is true.
// The default values is true.
FullText bool
// MaxResults optionally specifies the maximum results for indexing.
// The default is 1000.
MaxResults int
}
// ----------------------------------------------------------------------------
// Index
type LookupResult struct {
Decls HitList // package-level declarations (with snippets)
Others HitList // all other occurrences
}
type Index struct {
fset *token.FileSet // file set used during indexing; nil if no textindex
suffixes *suffixarray.Index // suffixes for concatenated sources; nil if no textindex
words map[string]*LookupResult // maps words to hit lists
alts map[string]*AltWords // maps canonical(words) to lists of alternative spellings
snippets []*Snippet // all snippets, indexed by snippet index
stats Statistics
importCount map[string]int // package path ("net/http") => count
packagePath map[string]map[string]bool // "template" => "text/template" => true
exports map[string]map[string]SpotKind // "net/http" => "ListenAndServe" => FuncDecl
idents map[SpotKind]map[string][]Ident
opts indexOptions
}
func canonical(w string) string { return strings.ToLower(w) }
// Somewhat arbitrary, but I figure low enough to not hurt disk-based filesystems
// consuming file descriptors, where some systems have low 256 or 512 limits.
// Go should have a built-in way to cap fd usage under the ulimit.
const (
maxOpenFiles = 200
maxOpenDirs = 50
)
func (c *Corpus) throttle() float64 {
if c.IndexThrottle <= 0 {
return 0.9
}
if c.IndexThrottle > 1.0 {
return 1.0
}
return c.IndexThrottle
}
// NewIndex creates a new index for the .go files provided by the corpus.
func (c *Corpus) NewIndex() *Index {
// initialize Indexer
// (use some reasonably sized maps to start)
x := &Indexer{
c: c,
fset: token.NewFileSet(),
fsOpenGate: make(chan bool, maxOpenFiles),
strings: make(map[string]string),
packages: make(map[Pak]*Pak, 256),
words: make(map[string]*IndexResult, 8192),
throttle: util.NewThrottle(c.throttle(), 100*time.Millisecond), // run at least 0.1s at a time
importCount: make(map[string]int),
packagePath: make(map[string]map[string]bool),
exports: make(map[string]map[string]SpotKind),
idents: make(map[SpotKind]map[string][]Ident, 4),
}
// index all files in the directories given by dirnames
var wg sync.WaitGroup // outstanding ReadDir + visitFile
dirGate := make(chan bool, maxOpenDirs)
for dirname := range c.fsDirnames() {
if c.IndexDirectory != nil && !c.IndexDirectory(dirname) {
continue
}
dirGate <- true
wg.Add(1)
go func(dirname string) {
defer func() { <-dirGate }()
defer wg.Done()
list, err := c.fs.ReadDir(dirname)
if err != nil {
log.Printf("ReadDir(%q): %v; skipping directory", dirname, err)
return // ignore this directory
}
for _, fi := range list {
wg.Add(1)
go func(fi os.FileInfo) {
defer wg.Done()
x.visitFile(dirname, fi)
}(fi)
}
}(dirname)
}
wg.Wait()
if !c.IndexFullText {
// the file set, the current file, and the sources are
// not needed after indexing if no text index is built -
// help GC and clear them
x.fset = nil
x.sources.Reset()
x.current = nil // contains reference to fset!
}
// for each word, reduce the RunLists into a LookupResult;
// also collect the word with its canonical spelling in a
// word list for later computation of alternative spellings
words := make(map[string]*LookupResult)
var wlist RunList
for w, h := range x.words {
decls := reduce(h.Decls)
others := reduce(h.Others)
words[w] = &LookupResult{
Decls: decls,
Others: others,
}
wlist = append(wlist, &wordPair{canonical(w), w})
x.throttle.Throttle()
}
x.stats.Words = len(words)
// reduce the word list {canonical(w), w} into
// a list of AltWords runs {canonical(w), {w}}
alist := wlist.reduce(lessWordPair, newAltWords)
// convert alist into a map of alternative spellings
alts := make(map[string]*AltWords)
for i := 0; i < len(alist); i++ {
a := alist[i].(*AltWords)
alts[a.Canon] = a
}
// create text index
var suffixes *suffixarray.Index
if c.IndexFullText {
suffixes = suffixarray.New(x.sources.Bytes())
}
// sort idents by the number of imports of their respective packages
for _, idMap := range x.idents {
for _, ir := range idMap {
sort.Sort(byImportCount{ir, x.importCount})
}
}
return &Index{
fset: x.fset,
suffixes: suffixes,
words: words,
alts: alts,
snippets: x.snippets,
stats: x.stats,
importCount: x.importCount,
packagePath: x.packagePath,
exports: x.exports,
idents: x.idents,
opts: indexOptions{
Docs: x.c.IndexDocs,
GoCode: x.c.IndexGoCode,
FullText: x.c.IndexFullText,
MaxResults: x.c.MaxResults,
},
}
}
var ErrFileIndexVersion = errors.New("file index version out of date")
const fileIndexVersion = 3
// fileIndex is the subset of Index that's gob-encoded for use by
// Index.Write and Index.Read.
type fileIndex struct {
Version int
Words map[string]*LookupResult
Alts map[string]*AltWords
Snippets []*Snippet
Fulltext bool
Stats Statistics
ImportCount map[string]int
PackagePath map[string]map[string]bool
Exports map[string]map[string]SpotKind
Idents map[SpotKind]map[string][]Ident
Opts indexOptions
}
func (x *fileIndex) Write(w io.Writer) error {
return gob.NewEncoder(w).Encode(x)
}
func (x *fileIndex) Read(r io.Reader) error {
return gob.NewDecoder(r).Decode(x)
}
// WriteTo writes the index x to w.
func (x *Index) WriteTo(w io.Writer) (n int64, err error) {
w = countingWriter{&n, w}
fulltext := false
if x.suffixes != nil {
fulltext = true
}
fx := fileIndex{
Version: fileIndexVersion,
Words: x.words,
Alts: x.alts,
Snippets: x.snippets,
Fulltext: fulltext,
Stats: x.stats,
ImportCount: x.importCount,
PackagePath: x.packagePath,
Exports: x.exports,
Idents: x.idents,
Opts: x.opts,
}
if err := fx.Write(w); err != nil {
return 0, err
}
if fulltext {
encode := func(x interface{}) error {
return gob.NewEncoder(w).Encode(x)
}
if err := x.fset.Write(encode); err != nil {
return 0, err
}
if err := x.suffixes.Write(w); err != nil {
return 0, err
}
}
return n, nil
}
// ReadFrom reads the index from r into x; x must not be nil.
// If r does not also implement io.ByteReader, it will be wrapped in a bufio.Reader.
// If the index is from an old version, the error is ErrFileIndexVersion.
func (x *Index) ReadFrom(r io.Reader) (n int64, err error) {
// We use the ability to read bytes as a plausible surrogate for buffering.
if _, ok := r.(io.ByteReader); !ok {
r = bufio.NewReader(r)
}
r = countingReader{&n, r.(byteReader)}
var fx fileIndex
if err := fx.Read(r); err != nil {
return n, err
}
if fx.Version != fileIndexVersion {
return 0, ErrFileIndexVersion
}
x.words = fx.Words
x.alts = fx.Alts
x.snippets = fx.Snippets
x.stats = fx.Stats
x.importCount = fx.ImportCount
x.packagePath = fx.PackagePath
x.exports = fx.Exports
x.idents = fx.Idents
x.opts = fx.Opts
if fx.Fulltext {
x.fset = token.NewFileSet()
decode := func(x interface{}) error {
return gob.NewDecoder(r).Decode(x)
}
if err := x.fset.Read(decode); err != nil {
return n, err
}
x.suffixes = new(suffixarray.Index)
if err := x.suffixes.Read(r); err != nil {
return n, err
}
}
return n, nil
}
// Stats returns index statistics.
func (x *Index) Stats() Statistics {
return x.stats
}
// ImportCount returns a map from import paths to how many times they were seen.
func (x *Index) ImportCount() map[string]int {
return x.importCount
}
// PackagePath returns a map from short package name to a set
// of full package path names that use that short package name.
func (x *Index) PackagePath() map[string]map[string]bool {
return x.packagePath
}
// Exports returns a map from full package path to exported
// symbol name to its type.
func (x *Index) Exports() map[string]map[string]SpotKind {
return x.exports
}
// Idents returns a map from identifier type to exported
// symbol name to the list of identifiers matching that name.
func (x *Index) Idents() map[SpotKind]map[string][]Ident {
return x.idents
}
func (x *Index) lookupWord(w string) (match *LookupResult, alt *AltWords) {
match = x.words[w]
alt = x.alts[canonical(w)]
// remove current spelling from alternatives
// (if there is no match, the alternatives do
// not contain the current spelling)
if match != nil && alt != nil {
alt = alt.filter(w)
}
return
}
// isIdentifier reports whether s is a Go identifier.
func isIdentifier(s string) bool {
for i, ch := range s {
if unicode.IsLetter(ch) || ch == '_' || i > 0 && unicode.IsDigit(ch) {
continue
}
return false
}
return len(s) > 0
}
// For a given query, which is either a single identifier or a qualified
// identifier, Lookup returns a SearchResult containing packages, a LookupResult, a
// list of alternative spellings, and identifiers, if any. Any and all results
// may be nil. If the query syntax is wrong, an error is reported.
func (x *Index) Lookup(query string) (*SearchResult, error) {
ss := strings.Split(query, ".")
// check query syntax
for _, s := range ss {
if !isIdentifier(s) {
return nil, errors.New("all query parts must be identifiers")
}
}
rslt := &SearchResult{
Query: query,
Idents: make(map[SpotKind][]Ident, 5),
}
// handle simple and qualified identifiers
switch len(ss) {
case 1:
ident := ss[0]
rslt.Hit, rslt.Alt = x.lookupWord(ident)
if rslt.Hit != nil {
// found a match - filter packages with same name
// for the list of packages called ident, if any
rslt.Pak = rslt.Hit.Others.filter(ident)
}
for k, v := range x.idents {
const rsltLimit = 50
ids := byImportCount{v[ident], x.importCount}
rslt.Idents[k] = ids.top(rsltLimit)
}
case 2:
pakname, ident := ss[0], ss[1]
rslt.Hit, rslt.Alt = x.lookupWord(ident)
if rslt.Hit != nil {
// found a match - filter by package name
// (no paks - package names are not qualified)
decls := rslt.Hit.Decls.filter(pakname)
others := rslt.Hit.Others.filter(pakname)
rslt.Hit = &LookupResult{decls, others}
}
for k, v := range x.idents {
ids := byImportCount{v[ident], x.importCount}
rslt.Idents[k] = ids.filter(pakname)
}
default:
return nil, errors.New("query is not a (qualified) identifier")
}
return rslt, nil
}
func (x *Index) Snippet(i int) *Snippet {
// handle illegal snippet indices gracefully
if 0 <= i && i < len(x.snippets) {
return x.snippets[i]
}
return nil
}
type positionList []struct {
filename string
line int
}
func (list positionList) Len() int { return len(list) }
func (list positionList) Less(i, j int) bool { return list[i].filename < list[j].filename }
func (list positionList) Swap(i, j int) { list[i], list[j] = list[j], list[i] }
// unique returns the list sorted and with duplicate entries removed
func unique(list []int) []int {
sort.Ints(list)
var last int
i := 0
for _, x := range list {
if i == 0 || x != last {
last = x
list[i] = x
i++
}
}
return list[0:i]
}
// A FileLines value specifies a file and line numbers within that file.
type FileLines struct {
Filename string
Lines []int
}
// LookupRegexp returns the number of matches and the matches where a regular
// expression r is found in the full text index. At most n matches are
// returned (thus found <= n).
func (x *Index) LookupRegexp(r *regexp.Regexp, n int) (found int, result []FileLines) {
if x.suffixes == nil || n <= 0 {
return
}
// n > 0
var list positionList
// FindAllIndex may returns matches that span across file boundaries.
// Such matches are unlikely, buf after eliminating them we may end up
// with fewer than n matches. If we don't have enough at the end, redo
// the search with an increased value n1, but only if FindAllIndex
// returned all the requested matches in the first place (if it
// returned fewer than that there cannot be more).
for n1 := n; found < n; n1 += n - found {
found = 0
matches := x.suffixes.FindAllIndex(r, n1)
// compute files, exclude matches that span file boundaries,
// and map offsets to file-local offsets
list = make(positionList, len(matches))
for _, m := range matches {
// by construction, an offset corresponds to the Pos value
// for the file set - use it to get the file and line
p := token.Pos(m[0])
if file := x.fset.File(p); file != nil {
if base := file.Base(); base <= m[1] && m[1] <= base+file.Size() {
// match [m[0], m[1]) is within the file boundaries
list[found].filename = file.Name()
list[found].line = file.Line(p)
found++
}
}
}
if found == n || len(matches) < n1 {
// found all matches or there's no chance to find more
break
}
}
list = list[0:found]
sort.Sort(list) // sort by filename
// collect matches belonging to the same file
var last string
var lines []int
addLines := func() {
if len(lines) > 0 {
// remove duplicate lines
result = append(result, FileLines{last, unique(lines)})
lines = nil
}
}
for _, m := range list {
if m.filename != last {
addLines()
last = m.filename
}
lines = append(lines, m.line)
}
addLines()
return
}
// invalidateIndex should be called whenever any of the file systems
// under godoc's observation change so that the indexer is kicked on.
func (c *Corpus) invalidateIndex() {
c.fsModified.Set(nil)
c.refreshMetadata()
}
// feedDirnames feeds the directory names of all directories
// under the file system given by root to channel c.
func (c *Corpus) feedDirnames(ch chan<- string) {
if dir, _ := c.fsTree.Get(); dir != nil {
for d := range dir.(*Directory).iter(false) {
ch <- d.Path
}
}
}
// fsDirnames() returns a channel sending all directory names
// of all the file systems under godoc's observation.
func (c *Corpus) fsDirnames() <-chan string {
ch := make(chan string, 256) // buffered for fewer context switches
go func() {
c.feedDirnames(ch)
close(ch)
}()
return ch
}
// CompatibleWith reports whether the Index x is compatible with the corpus
// indexing options set in c.
func (x *Index) CompatibleWith(c *Corpus) bool {
return x.opts.Docs == c.IndexDocs &&
x.opts.GoCode == c.IndexGoCode &&
x.opts.FullText == c.IndexFullText &&
x.opts.MaxResults == c.MaxResults
}
func (c *Corpus) readIndex(filenames string) error {
matches, err := filepath.Glob(filenames)
if err != nil {
return err
} else if matches == nil {
return fmt.Errorf("no index files match %q", filenames)
}
sort.Strings(matches) // make sure files are in the right order
files := make([]io.Reader, 0, len(matches))
for _, filename := range matches {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
files = append(files, f)
}
return c.ReadIndexFrom(io.MultiReader(files...))
}
// ReadIndexFrom sets the current index from the serialized version found in r.
func (c *Corpus) ReadIndexFrom(r io.Reader) error {
x := new(Index)
if _, err := x.ReadFrom(r); err != nil {
return err
}
if !x.CompatibleWith(c) {
return fmt.Errorf("index file options are incompatible: %v", x.opts)
}
c.searchIndex.Set(x)
return nil
}
func (c *Corpus) UpdateIndex() {
if c.Verbose {
log.Printf("updating index...")
}
start := time.Now()
index := c.NewIndex()
stop := time.Now()
c.searchIndex.Set(index)
if c.Verbose {
secs := stop.Sub(start).Seconds()
stats := index.Stats()
log.Printf("index updated (%gs, %d bytes of source, %d files, %d lines, %d unique words, %d spots)",
secs, stats.Bytes, stats.Files, stats.Lines, stats.Words, stats.Spots)
}
memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)
if c.Verbose {
log.Printf("before GC: bytes = %d footprint = %d", memstats.HeapAlloc, memstats.Sys)
}
runtime.GC()
runtime.ReadMemStats(memstats)
if c.Verbose {
log.Printf("after GC: bytes = %d footprint = %d", memstats.HeapAlloc, memstats.Sys)
}
}
// RunIndexer runs forever, indexing.
func (c *Corpus) RunIndexer() {
// initialize the index from disk if possible
if c.IndexFiles != "" {
c.initFSTree()
if err := c.readIndex(c.IndexFiles); err != nil {
log.Printf("error reading index from file %s: %v", c.IndexFiles, err)
}
return
}
// Repeatedly update the package directory tree and index.
for {
c.initFSTree()
c.UpdateIndex()
if c.IndexInterval < 0 {
return
}
delay := 5 * time.Minute // by default, reindex every 5 minutes
if c.IndexInterval > 0 {
delay = c.IndexInterval
}
time.Sleep(delay)
}
}
type countingWriter struct {
n *int64
w io.Writer
}
func (c countingWriter) Write(p []byte) (n int, err error) {
n, err = c.w.Write(p)
*c.n += int64(n)
return
}
type byteReader interface {
io.Reader
io.ByteReader
}
type countingReader struct {
n *int64
r byteReader
}
func (c countingReader) Read(p []byte) (n int, err error) {
n, err = c.r.Read(p)
*c.n += int64(n)
return
}
func (c countingReader) ReadByte() (b byte, err error) {
b, err = c.r.ReadByte()
*c.n += 1
return
}
| tools/godoc/index.go/0 | {
"file_path": "tools/godoc/index.go",
"repo_id": "tools",
"token_count": 16235
} | 718 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package godoc
// ----------------------------------------------------------------------------
// SpotInfo
// A SpotInfo value describes a particular identifier spot in a given file;
// It encodes three values: the SpotKind (declaration or use), a line or
// snippet index "lori", and whether it's a line or index.
//
// The following encoding is used:
//
// bits 32 4 1 0
// value [lori|kind|isIndex]
type SpotInfo uint32
// SpotKind describes whether an identifier is declared (and what kind of
// declaration) or used.
type SpotKind uint32
const (
PackageClause SpotKind = iota
ImportDecl
ConstDecl
TypeDecl
VarDecl
FuncDecl
MethodDecl
Use
nKinds
)
var (
// These must match the SpotKind values above.
name = []string{
"Packages",
"Imports",
"Constants",
"Types",
"Variables",
"Functions",
"Methods",
"Uses",
"Unknown",
}
)
func (x SpotKind) Name() string { return name[x] }
func init() {
// sanity check: if nKinds is too large, the SpotInfo
// accessor functions may need to be updated
if nKinds > 8 {
panic("internal error: nKinds > 8")
}
}
// makeSpotInfo makes a SpotInfo.
func makeSpotInfo(kind SpotKind, lori int, isIndex bool) SpotInfo {
// encode lori: bits [4..32)
x := SpotInfo(lori) << 4
if int(x>>4) != lori {
// lori value doesn't fit - since snippet indices are
// most certainly always smaller then 1<<28, this can
// only happen for line numbers; give it no line number (= 0)
x = 0
}
// encode kind: bits [1..4)
x |= SpotInfo(kind) << 1
// encode isIndex: bit 0
if isIndex {
x |= 1
}
return x
}
func (x SpotInfo) Kind() SpotKind { return SpotKind(x >> 1 & 7) }
func (x SpotInfo) Lori() int { return int(x >> 4) }
func (x SpotInfo) IsIndex() bool { return x&1 != 0 }
| tools/godoc/spot.go/0 | {
"file_path": "tools/godoc/spot.go",
"repo_id": "tools",
"token_count": 660
} | 719 |
<!--
Copyright 2009 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{{$query_url := urlquery .Query}}
{{if not .Idents}}
{{with .Pak}}
<h2 id="Packages">Package {{html $.Query}}</h2>
<p>
<table class="layout">
{{range .}}
{{$pkg_html := pkgLink .Pak.Path | html}}
<tr><td><a href="/{{$pkg_html}}">{{$pkg_html}}</a></td></tr>
{{end}}
</table>
</p>
{{end}}
{{end}}
{{with .Hit}}
{{with .Decls}}
<h2 id="Global">Package-level declarations</h2>
{{range .}}
{{$pkg_html := pkgLink .Pak.Path | html}}
<h3 id="Global_{{$pkg_html}}">package <a href="/{{$pkg_html}}">{{html .Pak.Name}}</a></h3>
{{range .Files}}
{{$file := .File.Path}}
{{range .Groups}}
{{range .}}
{{$line := infoLine .}}
<a href="{{queryLink $file $query_url $line | html}}">{{$file}}:{{$line}}</a>
{{infoSnippet_html .}}
{{end}}
{{end}}
{{end}}
{{end}}
{{end}}
{{with .Others}}
<h2 id="Local">Local declarations and uses</h2>
{{range .}}
{{$pkg_html := pkgLink .Pak.Path | html}}
<h3 id="Local_{{$pkg_html}}">package <a href="/{{$pkg_html}}">{{html .Pak.Name}}</a></h3>
{{range .Files}}
{{$file := .File.Path}}
<a href="{{queryLink $file $query_url 0 | html}}">{{$file}}</a>
<table class="layout">
{{range .Groups}}
<tr>
<td width="25"></td>
<th align="left" valign="top">{{index . 0 | infoKind_html}}</th>
<td align="left" width="4"></td>
<td>
{{range .}}
{{$line := infoLine .}}
<a href="{{queryLink $file $query_url $line | html}}">{{$line}}</a>
{{end}}
</td>
</tr>
{{end}}
</table>
{{end}}
{{end}}
{{end}}
{{end}}
| tools/godoc/static/searchcode.html/0 | {
"file_path": "tools/godoc/static/searchcode.html",
"repo_id": "tools",
"token_count": 818
} | 720 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package mapfs file provides an implementation of the FileSystem
// interface based on the contents of a map[string]string.
package mapfs // import "golang.org/x/tools/godoc/vfs/mapfs"
import (
"fmt"
"io"
"os"
pathpkg "path"
"sort"
"strings"
"time"
"golang.org/x/tools/godoc/vfs"
)
// New returns a new FileSystem from the provided map.
// Map keys must be forward slash-separated paths with
// no leading slash, such as "file1.txt" or "dir/file2.txt".
// New panics if any of the paths contain a leading slash.
func New(m map[string]string) vfs.FileSystem {
// Verify all provided paths are relative before proceeding.
var pathsWithLeadingSlash []string
for p := range m {
if strings.HasPrefix(p, "/") {
pathsWithLeadingSlash = append(pathsWithLeadingSlash, p)
}
}
if len(pathsWithLeadingSlash) > 0 {
panic(fmt.Errorf("mapfs.New: invalid paths with a leading slash: %q", pathsWithLeadingSlash))
}
return mapFS(m)
}
// mapFS is the map based implementation of FileSystem
type mapFS map[string]string
func (fs mapFS) String() string { return "mapfs" }
func (fs mapFS) RootType(p string) vfs.RootType {
return ""
}
func (fs mapFS) Close() error { return nil }
func filename(p string) string {
return strings.TrimPrefix(p, "/")
}
func (fs mapFS) Open(p string) (vfs.ReadSeekCloser, error) {
b, ok := fs[filename(p)]
if !ok {
return nil, os.ErrNotExist
}
return nopCloser{strings.NewReader(b)}, nil
}
func fileInfo(name, contents string) os.FileInfo {
return mapFI{name: pathpkg.Base(name), size: len(contents)}
}
func dirInfo(name string) os.FileInfo {
return mapFI{name: pathpkg.Base(name), dir: true}
}
func (fs mapFS) Lstat(p string) (os.FileInfo, error) {
b, ok := fs[filename(p)]
if ok {
return fileInfo(p, b), nil
}
ents, _ := fs.ReadDir(p)
if len(ents) > 0 {
return dirInfo(p), nil
}
return nil, os.ErrNotExist
}
func (fs mapFS) Stat(p string) (os.FileInfo, error) {
return fs.Lstat(p)
}
// slashdir returns path.Dir(p), but special-cases paths not beginning
// with a slash to be in the root.
func slashdir(p string) string {
d := pathpkg.Dir(p)
if d == "." {
return "/"
}
if strings.HasPrefix(p, "/") {
return d
}
return "/" + d
}
func (fs mapFS) ReadDir(p string) ([]os.FileInfo, error) {
p = pathpkg.Clean(p)
var ents []string
fim := make(map[string]os.FileInfo) // base -> fi
for fn, b := range fs {
dir := slashdir(fn)
isFile := true
var lastBase string
for {
if dir == p {
base := lastBase
if isFile {
base = pathpkg.Base(fn)
}
if fim[base] == nil {
var fi os.FileInfo
if isFile {
fi = fileInfo(fn, b)
} else {
fi = dirInfo(base)
}
ents = append(ents, base)
fim[base] = fi
}
}
if dir == "/" {
break
} else {
isFile = false
lastBase = pathpkg.Base(dir)
dir = pathpkg.Dir(dir)
}
}
}
if len(ents) == 0 {
return nil, os.ErrNotExist
}
sort.Strings(ents)
var list []os.FileInfo
for _, dir := range ents {
list = append(list, fim[dir])
}
return list, nil
}
// mapFI is the map-based implementation of FileInfo.
type mapFI struct {
name string
size int
dir bool
}
func (fi mapFI) IsDir() bool { return fi.dir }
func (fi mapFI) ModTime() time.Time { return time.Time{} }
func (fi mapFI) Mode() os.FileMode {
if fi.IsDir() {
return 0755 | os.ModeDir
}
return 0444
}
func (fi mapFI) Name() string { return pathpkg.Base(fi.name) }
func (fi mapFI) Size() int64 { return int64(fi.size) }
func (fi mapFI) Sys() interface{} { return nil }
type nopCloser struct {
io.ReadSeeker
}
func (nc nopCloser) Close() error { return nil }
| tools/godoc/vfs/mapfs/mapfs.go/0 | {
"file_path": "tools/godoc/vfs/mapfs/mapfs.go",
"repo_id": "tools",
"token_count": 1530
} | 721 |
# Gopls: Completion
TODO(golang/go#62022): document
| tools/gopls/doc/features/completion.md/0 | {
"file_path": "tools/gopls/doc/features/completion.md",
"repo_id": "tools",
"token_count": 24
} | 722 |
# gopls/v0.16.0
<!-- TODO: update this instruction once v0.16.0 is released.
Also, tweak the img URLs when publishing to GitHub Releases:
https://raw.githubusercontent.com/golang/v0.16.0/gopls/doc/ etc
-->
```
go install golang.org/x/tools/gopls@v0.16.0-pre.2
```
This release includes several features and bug fixes, and is the first
version of gopls to support Go 1.23. To install it, run:
## New support policy; end of support for Go 1.19 and Go 1.20
**TL;DR: We are narrowing gopls' support window, but this is unlikely to
affect you as long as you use at least Go 1.21 to build gopls. This doesn't
affect gopls' support for the code you are writing.**
This is the last release of gopls that may be built with Go 1.19 or Go 1.20,
and also the last to support integrating with go command versions 1.19 and
1.20. If built or used with either of these Go versions, it will display
a message advising the user to upgrade.
When using gopls, there are three versions to be aware of:
1. The _gopls build go version_: the version of Go used to build gopls.
2. The _go command version_: the version of the go list command executed by
gopls to load information about your workspace.
3. The _language version_: the version in the go directive of the current
file's enclosing go.mod file, which determines the file's Go language
semantics.
This gopls release, v0.16.0, is the final release to support Go 1.19 and Go
1.20 as the _gopls build go version_ or _go command version_. There is no
change to gopls' support for all _language versions_--in fact this support has
somewhat improved with the addition of the `stdversion` analyzer (see below).
Starting with gopls@v0.17.0, which will be released after Go 1.23.0 is released
in August, gopls will only support the latest version of Go as the
_gopls build go version_.
However, thanks to the [forward compatibility](https://go.dev/blog/toolchain)
added to Go 1.21, any necessary toolchain upgrade should be handled
automatically for users of Go 1.21 or later, just like any other dependency.
Additionally, we are reducing our _go command version_ support window from
4 versions to 3. Note that this means if you have at least Go 1.21 installed on
your system, you should still be able to `go install` and use gopls@v0.17.0.
We have no plans to ever change our _language version_ support: we expect that
gopls will always support developing programs that target _any_ Go version.
By focusing on building gopls with the latest Go version, we can significantly
reduce our maintenance burden and help improve the stability of future gopls
releases. See the newly updated
[support policy](https://github.com/golang/tools/tree/master/gopls#support-policy)
for details. Please comment on golang/go#65917 if
you have concerns about this change.
## Configuration changes
- The experimental `allowImplicitNetworkAccess` setting is deprecated (but not
yet removed). Please comment on golang/go#66861 if you use this
setting and would be impacted by its removal.
## New features
### Go 1.23 support
This version of gopls is the first to support the new language features of Go 1.23,
including
[range-over-func](https://go.dev/wiki/RangefuncExperiment) iterators
and support for the
[`godebug` directive](https://go.dev/ref/mod#go-mod-file-godebug)
in go.mod files.
### Integrated documentation viewer
Gopls now offers a "Browse documentation" code action that opens a
local web page displaying the generated documentation for Go packages
and symbols in a form similar to https://pkg.go.dev.
The package or symbol is chosen based on the current selection.
Use this feature to preview the marked-up documentation as you prepare API
changes, or to read the documentation for locally edited packages,
even ones that have not yet been saved. Reload the page after an edit
to see updated documentation.
<img title="Browse documentation for package" src="../assets/code-action-doc.png" width="80%">
As in `pkg.go.dev`, the heading for each symbol contains a link to the
source code of its declaration. In `pkg.go.dev`, these links would refer
to a source code page on a site such as GitHub or Google Code Search.
However, in gopls' internal viewer, clicking on one of these links will
cause your editor to navigate to the declaration.
(This feature requires that your LSP client honors the `showDocument` downcall.)
<img title="Symbol links navigate your editor to the declaration" src="../assets/browse-pkg-doc.png" width="80%">
Editor support:
- VS Code: use the "Source action > Browse documentation for func fmt.Println" menu item.
Note: source links navigate the editor but don't yet raise the window yet.
Please upvote microsoft/vscode#208093 and microsoft/vscode#207634 (temporarily closed).
- Emacs: requires eglot v1.17. Use `M-x go-browse-doc` from github.com/dominikh/go-mode.el.
The `linksInHover` setting now supports a new value, `"gopls"`,
that causes documentation links in the the Markdown output
of the Hover operation to link to gopls' internal doc viewer.
### Browse free symbols
Gopls offers another web-based code action, "Browse free symbols",
which displays the free symbols referenced by the selected code.
A symbol is "free" if it is referenced within the selection but
declared outside of it. The free symbols that are variables are
approximately the set of parameters that would be needed if the block
were extracted into its own function.
Even when you don't intend to extract a block into a new function,
this information can help you to tell at a glance what names a block
of code depends on.
Each dotted path of identifiers (such as `file.Name.Pos`) is reported
as a separate item, so that you can see which parts of a complex
type are actually needed.
The free symbols of the body of a function may reveal that
only a small part (a single field of a struct, say) of one of the
function's parameters is used, allowing you to simplify and generalize
the function by choosing a different type for that parameter.
<img title="Browse free symbols" src="../assets/browse-free-symbols.png" width="80%">
Editor support:
- VS Code: use the `Source action > Browse free symbols` menu item.
- Emacs: requires eglot v1.17. Use `M-x go-browse-freesymbols` from github.com/dominikh/go-mode.el.
### Browse assembly
Gopls offers a third web-based code action, "Browse assembly for f",
which displays an assembly listing of the declaration of the function
f enclosing the selected code, plus any nested functions such as
function literals or deferred calls.
Gopls invokes the compiler to generate the report;
reloading the page updates the report.
The machine architecture is determined by the build
configuration that gopls selects for the current file.
This is usually the same as your machine's GOARCH unless you are
working in a file with `go:build` tags for a different architecture.
<img title="Browse assembly for function" src="../assets/browse-assembly.png" width="80%">
Gopls cannot yet display assembly for generic functions:
generic functions are not fully compiled until they are instantiated,
but any function declaration enclosing the selection cannot be an
instantiated generic function.
<!-- Clearly the ideal UX for generic functions is to use the function
symbol under the cursor, e.g. Vector[string], rather than the
enclosing function; but computing the name of the linker symbol
remains a challenge. -->
Editor support:
- VS Code: use the "Source action > Browse assembly for f" menu item.
- Emacs: requires eglot v1.17. Use `M-x go-browse-assembly` from github.com/dominikh/go-mode.el.
### `unusedwrite` analyzer
The new
[unusedwrite](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/unusedwrite)
analyzer reports assignments, often to fields of structs, that have no
effect because, for example, the struct is never used again:
```go
func scheme(host string) string {
u := &url.URL{
Host: host, // "unused write to field Host" (no need to construct a URL)
Scheme: "https:",
}
return u.Scheme
}
```
This is at best an indication that the code is unnecessarily complex
(for instance, some dead code could be removed), but often indicates a
bug, as in this example:
```go
type S struct { x int }
func (s S) set(x int) {
s.x = x // "unused write to field x" (s should be a *S pointer)
}
```
### `stdversion` analyzer
The new
[`stdversion`](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/stdversion)
analyzer warns about the use of too-new standard library symbols based on the
version of the `go` directive in your `go.mod` file. This improves our support
for older _language versions_ (see above), even when gopls is built with
a recent Go version.
Consider the go.mod file and Go file below.
The declaration of `var `alias refers to a type, `types.Alias`,
introduced in go1.22, but the file belongs to a module that requires
only go1.21, so the analyzer reports a diagnostic:
```
module example.com
go 1.21
```
```go
package p
import "go/types"
var alias types.Alias // types.Alias requires go1.22 or later (module is go1.21)
```
When an individual file is build-tagged for a release of Go other than
than module's version, the analyzer will apply appropriate checks for
the file's version.
### Two more vet analyzers
The [framepointer](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/framepointer)
and [sigchanyzer](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/sigchanyzer)
analyzers have long been part of go vet's suite,
but had been overlooked in previous versions of gopls.
Henceforth, gopls will always include any analyzers run by vet.
### Hover shows size/offset info, and struct tags
Hovering over the identifier that declares a type or struct field now
displays the size information for the type:
<img title="struct size info" src="../assets/hover-size-struct.png">
and the offset information for the field:
<img title="field size/offset info" src="../assets/hover-size-field.png">
In addition, it reports the percentage of wasted space due to
suboptimal ordering of struct fields, if this figure is 20% or higher:
<img title="a struct with wasted space" src="../assets/hover-size-wasteful.png">
In the struct above, alignment rules require each of the two boolean
fields (1 byte) to occupy a complete word (8 bytes), leading to (7 +
7) / (3 * 8) = 58% waste.
Placing the two booleans together would save a word.
This information may be helpful when making space optimizations to
your data structures, or when reading assembly code.
Also, hovering over a reference to a field with a struct tag now also
display the tag:
<img title="hover shows field tag" src="../assets/hover-field-tag.png">
### Hover and "Go to Definition" work on symbols in doc comments
Go 1.19 added support for [doc links](https://go.dev/doc/comment#links),
allowing the doc comment for one symbol to reference another.
Gopls' Hover and Definition operations now treat these links just
like identifiers, so hovering over one will display information about
the symbol:
<img title="hover shows field tag" src="../assets/hover-doclink.png">
Similarly, "Go to definition" will navigate to its declaration.
Thanks to @rogeryk for contributing this feature.
## Bugs fixed
## Thank you to our contributors!
@guodongli-google for the `unusedwrite` analyzer.
TODO: they're a xoogler; is there a more current GH account?
@rogeryk
| tools/gopls/doc/release/v0.16.0.md/0 | {
"file_path": "tools/gopls/doc/release/v0.16.0.md",
"repo_id": "tools",
"token_count": 3217
} | 723 |
# Copyright 2019 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Build gopls, and run the govim integration tests. See README.md for
# instructions on how to use this.
substitutions:
# This bucket must be owned by the GCP project executing the build. If
# you are running this from your own project, override using --substitutions.
_RESULT_BUCKET: 'golang-gopls_integration_tests'
steps:
# Build gopls from source, to use with the govim integration tests.
- name: 'golang:1.14'
env: ['GOPROXY=https://proxy.golang.org']
dir: 'gopls'
args: ['go', 'build']
# Run the tests. Note that the script in this step does not return the exit
# code from `go test`, but rather saves it for use in the final step after
# uploading artifacts.
- name: 'gcr.io/$PROJECT_ID/govim-harness:3'
dir: '/src/govim'
volumes:
- name: artifacts
path: /artifacts
env:
- GOVIM_TESTSCRIPT_WORKDIR_ROOT=/artifacts
- VIM_FLAVOR=vim
args: ['/workspace/gopls/integration/govim/run_tests_for_cloudbuild.sh']
# The govim tests produce a large number of artifacts; tarball/gzip to reduce
# roundtrips and save space.
- name: 'ubuntu'
volumes:
- name: artifacts
path: /artifacts
args: ['tar', '-czf', 'artifacts.tar.gz', '/artifacts']
# Upload artifacts to GCS.
- name: 'gcr.io/cloud-builders/gsutil'
args: ['cp', 'artifacts.tar.gz', 'gs://${_RESULT_BUCKET}/govim/${BUILD_ID}/artifacts.tar.gz']
# Exit with the actual exit code of the integration tests.
- name: 'ubuntu'
args: ['bash', 'govim_test_result.sh']
# Write build logs to the same bucket as artifacts, so they can be more easily
# shared.
logsBucket: 'gs://${_RESULT_BUCKET}'
| tools/gopls/integration/govim/cloudbuild.yaml/0 | {
"file_path": "tools/gopls/integration/govim/cloudbuild.yaml",
"repo_id": "tools",
"token_count": 654
} | 724 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fillreturns
import (
"bytes"
_ "embed"
"fmt"
"go/ast"
"go/format"
"go/types"
"regexp"
"strings"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/gopls/internal/fuzzy"
"golang.org/x/tools/internal/analysisinternal"
)
//go:embed doc.go
var doc string
var Analyzer = &analysis.Analyzer{
Name: "fillreturns",
Doc: analysisinternal.MustExtractDoc(doc, "fillreturns"),
Run: run,
RunDespiteErrors: true,
URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/fillreturns",
}
func run(pass *analysis.Pass) (interface{}, error) {
info := pass.TypesInfo
if info == nil {
return nil, fmt.Errorf("nil TypeInfo")
}
outer:
for _, typeErr := range pass.TypeErrors {
// Filter out the errors that are not relevant to this analyzer.
if !FixesError(typeErr) {
continue
}
var file *ast.File
for _, f := range pass.Files {
if f.Pos() <= typeErr.Pos && typeErr.Pos <= f.End() {
file = f
break
}
}
if file == nil {
continue
}
// Get the end position of the error.
// (This heuristic assumes that the buffer is formatted,
// at least up to the end position of the error.)
var buf bytes.Buffer
if err := format.Node(&buf, pass.Fset, file); err != nil {
continue
}
typeErrEndPos := analysisinternal.TypeErrorEndPos(pass.Fset, buf.Bytes(), typeErr.Pos)
// TODO(rfindley): much of the error handling code below returns, when it
// should probably continue.
// Get the path for the relevant range.
path, _ := astutil.PathEnclosingInterval(file, typeErr.Pos, typeErrEndPos)
if len(path) == 0 {
return nil, nil
}
// Find the enclosing return statement.
var ret *ast.ReturnStmt
var retIdx int
for i, n := range path {
if r, ok := n.(*ast.ReturnStmt); ok {
ret = r
retIdx = i
break
}
}
if ret == nil {
return nil, nil
}
// Get the function type that encloses the ReturnStmt.
var enclosingFunc *ast.FuncType
for _, n := range path[retIdx+1:] {
switch node := n.(type) {
case *ast.FuncLit:
enclosingFunc = node.Type
case *ast.FuncDecl:
enclosingFunc = node.Type
}
if enclosingFunc != nil {
break
}
}
if enclosingFunc == nil || enclosingFunc.Results == nil {
continue
}
// Skip any generic enclosing functions, since type parameters don't
// have 0 values.
// TODO(rfindley): We should be able to handle this if the return
// values are all concrete types.
if tparams := enclosingFunc.TypeParams; tparams != nil && tparams.NumFields() > 0 {
return nil, nil
}
// Find the function declaration that encloses the ReturnStmt.
var outer *ast.FuncDecl
for _, p := range path {
if p, ok := p.(*ast.FuncDecl); ok {
outer = p
break
}
}
if outer == nil {
return nil, nil
}
// Skip any return statements that contain function calls with multiple
// return values.
for _, expr := range ret.Results {
e, ok := expr.(*ast.CallExpr)
if !ok {
continue
}
if tup, ok := info.TypeOf(e).(*types.Tuple); ok && tup.Len() > 1 {
continue outer
}
}
// Duplicate the return values to track which values have been matched.
remaining := make([]ast.Expr, len(ret.Results))
copy(remaining, ret.Results)
fixed := make([]ast.Expr, len(enclosingFunc.Results.List))
// For each value in the return function declaration, find the leftmost element
// in the return statement that has the desired type. If no such element exists,
// fill in the missing value with the appropriate "zero" value.
// Beware that type information may be incomplete.
var retTyps []types.Type
for _, ret := range enclosingFunc.Results.List {
retTyp := info.TypeOf(ret.Type)
if retTyp == nil {
return nil, nil
}
retTyps = append(retTyps, retTyp)
}
matches := analysisinternal.MatchingIdents(retTyps, file, ret.Pos(), info, pass.Pkg)
for i, retTyp := range retTyps {
var match ast.Expr
var idx int
for j, val := range remaining {
if t := info.TypeOf(val); t == nil || !matchingTypes(t, retTyp) {
continue
}
if !analysisinternal.IsZeroValue(val) {
match, idx = val, j
break
}
// If the current match is a "zero" value, we keep searching in
// case we find a non-"zero" value match. If we do not find a
// non-"zero" value, we will use the "zero" value.
match, idx = val, j
}
if match != nil {
fixed[i] = match
remaining = append(remaining[:idx], remaining[idx+1:]...)
} else {
names, ok := matches[retTyp]
if !ok {
return nil, fmt.Errorf("invalid return type: %v", retTyp)
}
// Find the identifier most similar to the return type.
// If no identifier matches the pattern, generate a zero value.
if best := fuzzy.BestMatch(retTyp.String(), names); best != "" {
fixed[i] = ast.NewIdent(best)
} else if zero := analysisinternal.ZeroValue(file, pass.Pkg, retTyp); zero != nil {
fixed[i] = zero
} else {
return nil, nil
}
}
}
// Remove any non-matching "zero values" from the leftover values.
var nonZeroRemaining []ast.Expr
for _, expr := range remaining {
if !analysisinternal.IsZeroValue(expr) {
nonZeroRemaining = append(nonZeroRemaining, expr)
}
}
// Append leftover return values to end of new return statement.
fixed = append(fixed, nonZeroRemaining...)
newRet := &ast.ReturnStmt{
Return: ret.Pos(),
Results: fixed,
}
// Convert the new return statement AST to text.
var newBuf bytes.Buffer
if err := format.Node(&newBuf, pass.Fset, newRet); err != nil {
return nil, err
}
pass.Report(analysis.Diagnostic{
Pos: typeErr.Pos,
End: typeErrEndPos,
Message: typeErr.Msg,
SuggestedFixes: []analysis.SuggestedFix{{
Message: "Fill in return values",
TextEdits: []analysis.TextEdit{{
Pos: ret.Pos(),
End: ret.End(),
NewText: newBuf.Bytes(),
}},
}},
})
}
return nil, nil
}
func matchingTypes(want, got types.Type) bool {
if want == got || types.Identical(want, got) {
return true
}
// Code segment to help check for untyped equality from (golang/go#32146).
if rhs, ok := want.(*types.Basic); ok && rhs.Info()&types.IsUntyped > 0 {
if lhs, ok := got.Underlying().(*types.Basic); ok {
return rhs.Info()&types.IsConstType == lhs.Info()&types.IsConstType
}
}
return types.AssignableTo(want, got) || types.ConvertibleTo(want, got)
}
// Error messages have changed across Go versions. These regexps capture recent
// incarnations.
//
// TODO(rfindley): once error codes are exported and exposed via go/packages,
// use error codes rather than string matching here.
var wrongReturnNumRegexes = []*regexp.Regexp{
regexp.MustCompile(`wrong number of return values \(want (\d+), got (\d+)\)`),
regexp.MustCompile(`too many return values`),
regexp.MustCompile(`not enough return values`),
}
func FixesError(err types.Error) bool {
msg := strings.TrimSpace(err.Msg)
for _, rx := range wrongReturnNumRegexes {
if rx.MatchString(msg) {
return true
}
}
return false
}
| tools/gopls/internal/analysis/fillreturns/fillreturns.go/0 | {
"file_path": "tools/gopls/internal/analysis/fillreturns/fillreturns.go",
"repo_id": "tools",
"token_count": 2872
} | 725 |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package infertypeargs
import (
"go/ast"
"go/token"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
"golang.org/x/tools/internal/typeparams"
"golang.org/x/tools/internal/versions"
)
const Doc = `check for unnecessary type arguments in call expressions
Explicit type arguments may be omitted from call expressions if they can be
inferred from function arguments, or from other type arguments:
func f[T any](T) {}
func _() {
f[string]("foo") // string could be inferred
}
`
var Analyzer = &analysis.Analyzer{
Name: "infertypeargs",
Doc: Doc,
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/infertypeargs",
}
func run(pass *analysis.Pass) (any, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
for _, diag := range diagnose(pass.Fset, inspect, token.NoPos, token.NoPos, pass.Pkg, pass.TypesInfo) {
pass.Report(diag)
}
return nil, nil
}
// Diagnose reports diagnostics describing simplifications to type
// arguments overlapping with the provided start and end position.
//
// If start or end is token.NoPos, the corresponding bound is not checked
// (i.e. if both start and end are NoPos, all call expressions are considered).
func diagnose(fset *token.FileSet, inspect *inspector.Inspector, start, end token.Pos, pkg *types.Package, info *types.Info) []analysis.Diagnostic {
var diags []analysis.Diagnostic
nodeFilter := []ast.Node{(*ast.CallExpr)(nil)}
inspect.Preorder(nodeFilter, func(node ast.Node) {
call := node.(*ast.CallExpr)
x, lbrack, indices, rbrack := typeparams.UnpackIndexExpr(call.Fun)
ident := calledIdent(x)
if ident == nil || len(indices) == 0 {
return // no explicit args, nothing to do
}
if (start.IsValid() && call.End() < start) || (end.IsValid() && call.Pos() > end) {
return // non-overlapping
}
// Confirm that instantiation actually occurred at this ident.
idata, ok := info.Instances[ident]
if !ok {
return // something went wrong, but fail open
}
instance := idata.Type
// Start removing argument expressions from the right, and check if we can
// still infer the call expression.
required := len(indices) // number of type expressions that are required
for i := len(indices) - 1; i >= 0; i-- {
var fun ast.Expr
if i == 0 {
// No longer an index expression: just use the parameterized operand.
fun = x
} else {
fun = typeparams.PackIndexExpr(x, lbrack, indices[:i], indices[i-1].End())
}
newCall := &ast.CallExpr{
Fun: fun,
Lparen: call.Lparen,
Args: call.Args,
Ellipsis: call.Ellipsis,
Rparen: call.Rparen,
}
info := &types.Info{
Instances: make(map[*ast.Ident]types.Instance),
}
versions.InitFileVersions(info)
if err := types.CheckExpr(fset, pkg, call.Pos(), newCall, info); err != nil {
// Most likely inference failed.
break
}
newIData := info.Instances[ident]
newInstance := newIData.Type
if !types.Identical(instance, newInstance) {
// The inferred result type does not match the original result type, so
// this simplification is not valid.
break
}
required = i
}
if required < len(indices) {
var s, e token.Pos
var edit analysis.TextEdit
if required == 0 {
s, e = lbrack, rbrack+1 // erase the entire index
edit = analysis.TextEdit{Pos: s, End: e}
} else {
s = indices[required].Pos()
e = rbrack
// erase from end of last arg to include last comma & white-spaces
edit = analysis.TextEdit{Pos: indices[required-1].End(), End: e}
}
// Recheck that our (narrower) fixes overlap with the requested range.
if (start.IsValid() && e < start) || (end.IsValid() && s > end) {
return // non-overlapping
}
diags = append(diags, analysis.Diagnostic{
Pos: s,
End: e,
Message: "unnecessary type arguments",
SuggestedFixes: []analysis.SuggestedFix{{
Message: "Simplify type arguments",
TextEdits: []analysis.TextEdit{edit},
}},
})
}
})
return diags
}
func calledIdent(x ast.Expr) *ast.Ident {
switch x := x.(type) {
case *ast.Ident:
return x
case *ast.SelectorExpr:
return x.Sel
}
return nil
}
| tools/gopls/internal/analysis/infertypeargs/infertypeargs.go/0 | {
"file_path": "tools/gopls/internal/analysis/infertypeargs/infertypeargs.go",
"repo_id": "tools",
"token_count": 1714
} | 726 |
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package norangeoverfunc
// TODO(adonovan): delete this when #67237 and dominikh/go-tools#1494 are fixed.
import (
_ "embed"
"fmt"
"go/ast"
"go/types"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "norangeoverfunc",
Doc: `norangeoverfunc fails if a package uses go1.23 range-over-func
Require it from any analyzer that cannot yet safely process this new feature.`,
Requires: []*analysis.Analyzer{inspect.Analyzer},
Run: run,
}
func run(pass *analysis.Pass) (any, error) {
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
filter := []ast.Node{(*ast.RangeStmt)(nil)}
// TODO(adonovan): opt: short circuit if not using go1.23.
var found *ast.RangeStmt
inspect.Preorder(filter, func(n ast.Node) {
if found == nil {
stmt := n.(*ast.RangeStmt)
if _, ok := pass.TypesInfo.TypeOf(stmt.X).Underlying().(*types.Signature); ok {
found = stmt
}
}
})
if found != nil {
return nil, fmt.Errorf("package %q uses go1.23 range-over-func; cannot build SSA or IR (#67237)",
pass.Pkg.Path())
}
return nil, nil
}
| tools/gopls/internal/analysis/norangeoverfunc/norangeoverfunc.go/0 | {
"file_path": "tools/gopls/internal/analysis/norangeoverfunc/norangeoverfunc.go",
"repo_id": "tools",
"token_count": 515
} | 727 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package undeclared
func x() int {
var z int
z = y // want "(undeclared name|undefined): y"
if z == m { // want "(undeclared name|undefined): m"
z = 1
}
if z == 1 {
z = 1
} else if z == n+1 { // want "(undeclared name|undefined): n"
z = 1
}
switch z {
case 10:
z = 1
case a: // want "(undeclared name|undefined): a"
z = 1
}
return z
}
| tools/gopls/internal/analysis/undeclaredname/testdata/src/a/a.go/0 | {
"file_path": "tools/gopls/internal/analysis/undeclaredname/testdata/src/a/a.go",
"repo_id": "tools",
"token_count": 204
} | 728 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package typeparams
import (
"bytes"
"fmt"
"net/http"
)
type parent[T any] interface {
n(f T)
}
type yuh[T any] struct {
a T
}
func (y *yuh[int]) n(f bool) {
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
func a[T comparable](i1 int, i2 T, i3 int) int { // want "unused parameter: i2"
i3 += i1
_ = func(z int) int { // want "unused parameter: z"
_ = 1
return 1
}
return i3
}
func b[T any](c bytes.Buffer) { // want "unused parameter: c"
_ = 1
}
func z[T http.ResponseWriter](h T, _ *http.Request) { // no report: func z is address-taken
fmt.Println("Before")
}
func l(h http.Handler) http.Handler { // want "unused parameter: h"
return http.HandlerFunc(z[http.ResponseWriter])
}
func mult(a, b int) int { // want "unused parameter: b"
a += 1
return a
}
func y[T any](a T) {
panic("yo")
}
| tools/gopls/internal/analysis/unusedparams/testdata/src/typeparams/typeparams.go/0 | {
"file_path": "tools/gopls/internal/analysis/unusedparams/testdata/src/typeparams/typeparams.go",
"repo_id": "tools",
"token_count": 399
} | 729 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"crypto/sha256"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"go/types"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"golang.org/x/mod/module"
"golang.org/x/sync/errgroup"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/gopls/internal/cache/metadata"
"golang.org/x/tools/gopls/internal/cache/parsego"
"golang.org/x/tools/gopls/internal/cache/typerefs"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/filecache"
"golang.org/x/tools/gopls/internal/label"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/gopls/internal/util/safetoken"
"golang.org/x/tools/gopls/internal/util/slices"
"golang.org/x/tools/internal/analysisinternal"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/gcimporter"
"golang.org/x/tools/internal/packagesinternal"
"golang.org/x/tools/internal/tokeninternal"
"golang.org/x/tools/internal/typesinternal"
"golang.org/x/tools/internal/versions"
)
// Various optimizations that should not affect correctness.
const (
preserveImportGraph = true // hold on to the import graph for open packages
)
type unit = struct{}
// A typeCheckBatch holds data for a logical type-checking operation, which may
// type-check many unrelated packages.
//
// It shares state such as parsed files and imports, to optimize type-checking
// for packages with overlapping dependency graphs.
type typeCheckBatch struct {
syntaxIndex map[PackageID]int // requested ID -> index in ids
pre preTypeCheck
post postTypeCheck
handles map[PackageID]*packageHandle // (immutable)
parseCache *parseCache
fset *token.FileSet // describes all parsed or imported files
cpulimit chan unit // concurrency limiter for CPU-bound operations
mu sync.Mutex
syntaxPackages map[PackageID]*futurePackage // results of processing a requested package; may hold (nil, nil)
importPackages map[PackageID]*futurePackage // package results to use for importing
}
// A futurePackage is a future result of type checking or importing a package,
// to be cached in a map.
//
// The goroutine that creates the futurePackage is responsible for evaluating
// its value, and closing the done channel.
type futurePackage struct {
done chan unit
v pkgOrErr
}
type pkgOrErr struct {
pkg *types.Package
err 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 (s *Snapshot) TypeCheck(ctx context.Context, ids ...PackageID) ([]*Package, error) {
pkgs := make([]*Package, len(ids))
var (
needIDs []PackageID // ids to type-check
indexes []int // original index of requested ids
)
// Check for existing active packages, as any package will do.
//
// This is also done inside forEachPackage, but doing it here avoids
// unnecessary set up for type checking (e.g. assembling the package handle
// graph).
for i, id := range ids {
if pkg := s.getActivePackage(id); pkg != nil {
pkgs[i] = pkg
} else {
needIDs = append(needIDs, id)
indexes = append(indexes, i)
}
}
post := func(i int, pkg *Package) {
pkgs[indexes[i]] = pkg
}
return pkgs, s.forEachPackage(ctx, needIDs, nil, post)
}
// getImportGraph returns a shared import graph use for this snapshot, or nil.
//
// This is purely an optimization: holding on to more imports allows trading
// memory for CPU and latency. Currently, getImportGraph returns an import
// graph containing all packages imported by open packages, since these are
// highly likely to be needed when packages change.
//
// Furthermore, since we memoize active packages, including their imports in
// the shared import graph means we don't run the risk of pinning duplicate
// copies of common imports, if active packages are computed in separate type
// checking batches.
func (s *Snapshot) getImportGraph(ctx context.Context) *importGraph {
if !preserveImportGraph {
return nil
}
s.mu.Lock()
// Evaluate the shared import graph for the snapshot. There are three major
// codepaths here:
//
// 1. importGraphDone == nil, importGraph == nil: it is this goroutine's
// responsibility to type-check the shared import graph.
// 2. importGraphDone == nil, importGraph != nil: it is this goroutine's
// responsibility to resolve the import graph, which may result in
// type-checking only if the existing importGraph (carried over from the
// preceding snapshot) is invalid.
// 3. importGraphDone != nil: some other goroutine is doing (1) or (2), wait
// for the work to be done.
done := s.importGraphDone
if done == nil {
done = make(chan unit)
s.importGraphDone = done
release := s.Acquire() // must acquire to use the snapshot asynchronously
go func() {
defer release()
importGraph, err := s.resolveImportGraph() // may be nil
if err != nil {
// resolveImportGraph operates on the background context, because it is
// a shared resource across the snapshot. If the snapshot is cancelled,
// don't log an error.
if s.backgroundCtx.Err() == nil {
event.Error(ctx, "computing the shared import graph", err)
}
importGraph = nil
}
s.mu.Lock()
s.importGraph = importGraph
s.mu.Unlock()
close(done)
}()
}
s.mu.Unlock()
select {
case <-done:
return s.importGraph
case <-ctx.Done():
return nil
}
}
// resolveImportGraph evaluates the shared import graph to use for
// type-checking in this snapshot. This may involve re-using the import graph
// of the previous snapshot (stored in s.importGraph), or computing a fresh
// import graph.
//
// resolveImportGraph should only be called from getImportGraph.
func (s *Snapshot) resolveImportGraph() (*importGraph, error) {
ctx := s.backgroundCtx
ctx, done := event.Start(event.Detach(ctx), "cache.resolveImportGraph")
defer done()
s.mu.Lock()
lastImportGraph := s.importGraph
s.mu.Unlock()
openPackages := make(map[PackageID]bool)
for _, fh := range s.Overlays() {
// golang/go#66145: don't call MetadataForFile here. This function, which
// builds a shared import graph, is an optimization. We don't want it to
// have the side effect of triggering a load.
//
// In the past, a call to MetadataForFile here caused a bunch of
// unnecessary loads in multi-root workspaces (and as a result, spurious
// diagnostics).
g := s.MetadataGraph()
var mps []*metadata.Package
for _, id := range g.IDs[fh.URI()] {
mps = append(mps, g.Packages[id])
}
metadata.RemoveIntermediateTestVariants(&mps)
for _, mp := range mps {
openPackages[mp.ID] = true
}
}
var openPackageIDs []PackageID
for id := range openPackages {
openPackageIDs = append(openPackageIDs, id)
}
handles, err := s.getPackageHandles(ctx, openPackageIDs)
if err != nil {
return nil, err
}
// Subtlety: we erase the upward cone of open packages from the shared import
// graph, to increase reusability.
//
// This is easiest to understand via an example: suppose A imports B, and B
// imports C. Now suppose A and B are open. If we preserve the entire set of
// shared deps by open packages, deps will be {B, C}. But this means that any
// change to the open package B will invalidate the shared import graph,
// meaning we will experience no benefit from sharing when B is edited.
// Consider that this will be a common scenario, when A is foo_test and B is
// foo. Better to just preserve the shared import C.
//
// With precise pruning, we may want to truncate this search based on
// reachability.
//
// TODO(rfindley): this logic could use a unit test.
volatileDeps := make(map[PackageID]bool)
var isVolatile func(*packageHandle) bool
isVolatile = func(ph *packageHandle) (volatile bool) {
if v, ok := volatileDeps[ph.mp.ID]; ok {
return v
}
defer func() {
volatileDeps[ph.mp.ID] = volatile
}()
if openPackages[ph.mp.ID] {
return true
}
for _, dep := range ph.mp.DepsByPkgPath {
if isVolatile(handles[dep]) {
return true
}
}
return false
}
for _, dep := range handles {
isVolatile(dep)
}
for id, volatile := range volatileDeps {
if volatile {
delete(handles, id)
}
}
// We reuse the last import graph if and only if none of the dependencies
// have changed. Doing better would involve analyzing dependencies to find
// subgraphs that are still valid. Not worth it, especially when in the
// common case nothing has changed.
unchanged := lastImportGraph != nil && len(handles) == len(lastImportGraph.depKeys)
var ids []PackageID
depKeys := make(map[PackageID]file.Hash)
for id, ph := range handles {
ids = append(ids, id)
depKeys[id] = ph.key
if unchanged {
prevKey, ok := lastImportGraph.depKeys[id]
unchanged = ok && prevKey == ph.key
}
}
if unchanged {
return lastImportGraph, nil
}
b, err := s.forEachPackageInternal(ctx, nil, ids, nil, nil, nil, handles)
if err != nil {
return nil, err
}
next := &importGraph{
fset: b.fset,
depKeys: depKeys,
imports: make(map[PackageID]pkgOrErr),
}
for id, fut := range b.importPackages {
if fut.v.pkg == nil && fut.v.err == nil {
panic(fmt.Sprintf("internal error: import node %s is not evaluated", id))
}
next.imports[id] = fut.v
}
return next, nil
}
// An importGraph holds selected results of a type-checking pass, to be re-used
// by subsequent snapshots.
type importGraph struct {
fset *token.FileSet // fileset used for type checking imports
depKeys map[PackageID]file.Hash // hash of direct dependencies for this graph
imports map[PackageID]pkgOrErr // results of type checking
}
// Package visiting functions used by forEachPackage; see the documentation of
// forEachPackage for details.
type (
preTypeCheck = func(int, *packageHandle) bool // false => don't type check
postTypeCheck = func(int, *Package)
)
// forEachPackage does a pre- and post- order traversal of the packages
// specified by ids using the provided pre and post functions.
//
// The pre func is optional. If set, pre is evaluated after the package
// handle has been constructed, but before type-checking. If pre returns false,
// type-checking is skipped for this package handle.
//
// post is called with a syntax package after type-checking completes
// successfully. It is only called if pre returned true.
//
// Both pre and post may be called concurrently.
func (s *Snapshot) forEachPackage(ctx context.Context, ids []PackageID, pre preTypeCheck, post postTypeCheck) error {
ctx, done := event.Start(ctx, "cache.forEachPackage", label.PackageCount.Of(len(ids)))
defer done()
var (
needIDs []PackageID // ids to type-check
indexes []int // original index of requested ids
)
// Check for existing active packages.
//
// Since gopls can't depend on package identity, any instance of the
// requested package must be ok to return.
//
// This is an optimization to avoid redundant type-checking: following
// changes to an open package many LSP clients send several successive
// requests for package information for the modified package (semantic
// tokens, code lens, inlay hints, etc.)
for i, id := range ids {
if pkg := s.getActivePackage(id); pkg != nil {
post(i, pkg)
} else {
needIDs = append(needIDs, id)
indexes = append(indexes, i)
}
}
if len(needIDs) == 0 {
return nil // short cut: many call sites do not handle empty ids
}
// Wrap the pre- and post- funcs to translate indices.
var pre2 preTypeCheck
if pre != nil {
pre2 = func(i int, ph *packageHandle) bool {
return pre(indexes[i], ph)
}
}
post2 := func(i int, pkg *Package) {
s.setActivePackage(pkg.metadata.ID, pkg)
post(indexes[i], pkg)
}
handles, err := s.getPackageHandles(ctx, needIDs)
if err != nil {
return err
}
impGraph := s.getImportGraph(ctx)
_, err = s.forEachPackageInternal(ctx, impGraph, nil, needIDs, pre2, post2, handles)
return err
}
// forEachPackageInternal is used by both forEachPackage and loadImportGraph to
// type-check a graph of packages.
//
// If a non-nil importGraph is provided, imports in this graph will be reused.
func (s *Snapshot) forEachPackageInternal(ctx context.Context, importGraph *importGraph, importIDs, syntaxIDs []PackageID, pre preTypeCheck, post postTypeCheck, handles map[PackageID]*packageHandle) (*typeCheckBatch, error) {
b := &typeCheckBatch{
pre: pre,
post: post,
handles: handles,
parseCache: s.view.parseCache,
fset: fileSetWithBase(reservedForParsing),
syntaxIndex: make(map[PackageID]int),
cpulimit: make(chan unit, runtime.GOMAXPROCS(0)),
syntaxPackages: make(map[PackageID]*futurePackage),
importPackages: make(map[PackageID]*futurePackage),
}
if importGraph != nil {
// Clone the file set every time, to ensure we do not leak files.
b.fset = tokeninternal.CloneFileSet(importGraph.fset)
// Pre-populate future cache with 'done' futures.
done := make(chan unit)
close(done)
for id, res := range importGraph.imports {
b.importPackages[id] = &futurePackage{done, res}
}
} else {
b.fset = fileSetWithBase(reservedForParsing)
}
for i, id := range syntaxIDs {
b.syntaxIndex[id] = i
}
// Start a single goroutine for each requested package.
//
// Other packages are reached recursively, and will not be evaluated if they
// are not needed.
var g errgroup.Group
for _, id := range importIDs {
id := id
g.Go(func() error {
_, err := b.getImportPackage(ctx, id)
return err
})
}
for i, id := range syntaxIDs {
i := i
id := id
g.Go(func() error {
_, err := b.handleSyntaxPackage(ctx, i, id)
return err
})
}
return b, g.Wait()
}
// TODO(rfindley): re-order the declarations below to read better from top-to-bottom.
// getImportPackage returns the *types.Package to use for importing the
// package referenced by id.
//
// This may be the package produced by type-checking syntax (as in the case
// where id is in the set of requested IDs), a package loaded from export data,
// or a package type-checked for import only.
func (b *typeCheckBatch) getImportPackage(ctx context.Context, id PackageID) (pkg *types.Package, err error) {
b.mu.Lock()
f, ok := b.importPackages[id]
if ok {
b.mu.Unlock()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-f.done:
return f.v.pkg, f.v.err
}
}
f = &futurePackage{done: make(chan unit)}
b.importPackages[id] = f
b.mu.Unlock()
defer func() {
f.v = pkgOrErr{pkg, err}
close(f.done)
}()
if index, ok := b.syntaxIndex[id]; ok {
pkg, err := b.handleSyntaxPackage(ctx, index, id)
if err != nil {
return nil, err
}
if pkg != nil {
return pkg, nil
}
// type-checking was short-circuited by the pre- func.
}
// unsafe cannot be imported or type-checked.
if id == "unsafe" {
return types.Unsafe, nil
}
ph := b.handles[id]
// Do a second check for "unsafe" defensively, due to golang/go#60890.
if ph.mp.PkgPath == "unsafe" {
// (This assertion is reached.)
bug.Reportf("encountered \"unsafe\" as %s (golang/go#60890)", id)
return types.Unsafe, nil
}
data, err := filecache.Get(exportDataKind, ph.key)
if err == filecache.ErrNotFound {
// No cached export data: type-check as fast as possible.
return b.checkPackageForImport(ctx, ph)
}
if err != nil {
return nil, fmt.Errorf("failed to read cache data for %s: %v", ph.mp.ID, err)
}
return b.importPackage(ctx, ph.mp, data)
}
// handleSyntaxPackage handles one package from the ids slice.
//
// If type checking occurred while handling the package, it returns the
// resulting types.Package so that it may be used for importing.
//
// handleSyntaxPackage returns (nil, nil) if pre returned false.
func (b *typeCheckBatch) handleSyntaxPackage(ctx context.Context, i int, id PackageID) (pkg *types.Package, err error) {
b.mu.Lock()
f, ok := b.syntaxPackages[id]
if ok {
b.mu.Unlock()
<-f.done
return f.v.pkg, f.v.err
}
f = &futurePackage{done: make(chan unit)}
b.syntaxPackages[id] = f
b.mu.Unlock()
defer func() {
f.v = pkgOrErr{pkg, err}
close(f.done)
}()
ph := b.handles[id]
if b.pre != nil && !b.pre(i, ph) {
return nil, nil // skip: export data only
}
// Wait for predecessors.
{
var g errgroup.Group
for _, depID := range ph.mp.DepsByPkgPath {
depID := depID
g.Go(func() error {
_, err := b.getImportPackage(ctx, depID)
return err
})
}
if err := g.Wait(); err != nil {
// Failure to import a package should not abort the whole operation.
// Stop only if the context was cancelled, a likely cause.
// Import errors will be reported as type diagnostics.
if ctx.Err() != nil {
return nil, ctx.Err()
}
}
}
// Wait to acquire a CPU token.
//
// Note: it is important to acquire this token only after awaiting
// predecessors, to avoid starvation.
select {
case <-ctx.Done():
return nil, ctx.Err()
case b.cpulimit <- unit{}:
defer func() {
<-b.cpulimit // release CPU token
}()
}
// Compute the syntax package.
p, err := b.checkPackage(ctx, ph)
if err != nil {
return nil, err
}
// Update caches.
go storePackageResults(ctx, ph, p) // ...and write all packages to disk
b.post(i, p)
return p.pkg.types, nil
}
// storePackageResults serializes and writes information derived from p to the
// file cache.
// The context is used only for logging; cancellation does not affect the operation.
func storePackageResults(ctx context.Context, ph *packageHandle, p *Package) {
toCache := map[string][]byte{
xrefsKind: p.pkg.xrefs(),
methodSetsKind: p.pkg.methodsets().Encode(),
diagnosticsKind: encodeDiagnostics(p.pkg.diagnostics),
}
if p.metadata.PkgPath != "unsafe" { // unsafe cannot be exported
exportData, err := gcimporter.IExportShallow(p.pkg.fset, p.pkg.types, bug.Reportf)
if err != nil {
bug.Reportf("exporting package %v: %v", p.metadata.ID, err)
} else {
toCache[exportDataKind] = exportData
}
} else if p.metadata.ID != "unsafe" {
// golang/go#60890: we should only ever see one variant of the "unsafe"
// package.
bug.Reportf("encountered \"unsafe\" as %s (golang/go#60890)", p.metadata.ID)
}
for kind, data := range toCache {
if err := filecache.Set(kind, ph.key, data); err != nil {
event.Error(ctx, fmt.Sprintf("storing %s data for %s", kind, ph.mp.ID), err)
}
}
}
// importPackage loads the given package from its export data in p.exportData
// (which must already be populated).
func (b *typeCheckBatch) importPackage(ctx context.Context, mp *metadata.Package, data []byte) (*types.Package, error) {
ctx, done := event.Start(ctx, "cache.typeCheckBatch.importPackage", label.Package.Of(string(mp.ID)))
defer done()
impMap := b.importMap(mp.ID)
thisPackage := types.NewPackage(string(mp.PkgPath), string(mp.Name))
getPackages := func(items []gcimporter.GetPackagesItem) error {
for i, item := range items {
var id PackageID
var pkg *types.Package
if item.Path == string(mp.PkgPath) {
id = mp.ID
pkg = thisPackage
// debugging issues #60904, #64235
if pkg.Name() != item.Name {
// This would mean that mp.Name != item.Name, so the
// manifest in the export data of mp.PkgPath is
// inconsistent with mp.Name. Or perhaps there
// are duplicate PkgPath items in the manifest?
return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904)",
pkg.Name(), item.Name, id, item.Path)
}
} else {
id = impMap[item.Path]
var err error
pkg, err = b.getImportPackage(ctx, id)
if err != nil {
return err
}
// We intentionally duplicate the bug.Errorf calls because
// telemetry tells us only the program counter, not the message.
// debugging issues #60904, #64235
if pkg.Name() != item.Name {
// This means that, while reading the manifest of the
// export data of mp.PkgPath, one of its indirect
// dependencies had a name that differs from the
// Metadata.Name
return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904)",
pkg.Name(), item.Name, id, item.Path)
}
}
items[i].Pkg = pkg
}
return nil
}
// Importing is potentially expensive, and might not encounter cancellations
// via dependencies (e.g. if they have already been evaluated).
if ctx.Err() != nil {
return nil, ctx.Err()
}
imported, err := gcimporter.IImportShallow(b.fset, getPackages, data, string(mp.PkgPath), bug.Reportf)
if err != nil {
return nil, fmt.Errorf("import failed for %q: %v", mp.ID, err)
}
return imported, nil
}
// checkPackageForImport type checks, but skips function bodies and does not
// record syntax information.
func (b *typeCheckBatch) checkPackageForImport(ctx context.Context, ph *packageHandle) (*types.Package, error) {
ctx, done := event.Start(ctx, "cache.typeCheckBatch.checkPackageForImport", label.Package.Of(string(ph.mp.ID)))
defer done()
onError := func(e error) {
// Ignore errors for exporting.
}
cfg := b.typesConfig(ctx, ph.localInputs, onError)
cfg.IgnoreFuncBodies = true
// Parse the compiled go files, bypassing the parse cache as packages checked
// for import are unlikely to get cache hits. Additionally, we can optimize
// parsing slightly by not passing parser.ParseComments.
pgfs := make([]*parsego.File, len(ph.localInputs.compiledGoFiles))
{
var group errgroup.Group
// Set an arbitrary concurrency limit; we want some parallelism but don't
// need GOMAXPROCS, as there is already a lot of concurrency among calls to
// checkPackageForImport.
//
// TODO(rfindley): is there a better way to limit parallelism here? We could
// have a global limit on the type-check batch, but would have to be very
// careful to avoid starvation.
group.SetLimit(4)
for i, fh := range ph.localInputs.compiledGoFiles {
i, fh := i, fh
group.Go(func() error {
pgf, err := parseGoImpl(ctx, b.fset, fh, parser.SkipObjectResolution, false)
pgfs[i] = pgf
return err
})
}
if err := group.Wait(); err != nil {
return nil, err // cancelled, or catastrophic error (e.g. missing file)
}
}
pkg := types.NewPackage(string(ph.localInputs.pkgPath), string(ph.localInputs.name))
check := types.NewChecker(cfg, b.fset, pkg, nil)
files := make([]*ast.File, len(pgfs))
for i, pgf := range pgfs {
files[i] = pgf.File
}
// Type checking is expensive, and we may not have encountered cancellations
// via parsing (e.g. if we got nothing but cache hits for parsed files).
if ctx.Err() != nil {
return nil, ctx.Err()
}
_ = check.Files(files) // ignore errors
// If the context was cancelled, we may have returned a ton of transient
// errors to the type checker. Swallow them.
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Asynchronously record export data.
go func() {
exportData, err := gcimporter.IExportShallow(b.fset, pkg, bug.Reportf)
if err != nil {
bug.Reportf("exporting package %v: %v", ph.mp.ID, err)
return
}
if err := filecache.Set(exportDataKind, ph.key, exportData); err != nil {
event.Error(ctx, fmt.Sprintf("storing export data for %s", ph.mp.ID), err)
}
}()
return pkg, nil
}
// importMap returns the map of package path -> package ID relative to the
// specified ID.
func (b *typeCheckBatch) importMap(id PackageID) map[string]PackageID {
impMap := make(map[string]PackageID)
var populateDeps func(*metadata.Package)
populateDeps = func(parent *metadata.Package) {
for _, id := range parent.DepsByPkgPath {
mp := b.handles[id].mp
if prevID, ok := impMap[string(mp.PkgPath)]; ok {
// debugging #63822
if prevID != mp.ID {
bug.Reportf("inconsistent view of dependencies")
}
continue
}
impMap[string(mp.PkgPath)] = mp.ID
populateDeps(mp)
}
}
mp := b.handles[id].mp
populateDeps(mp)
return impMap
}
// A packageHandle holds inputs required to compute a Package, including
// metadata, derived diagnostics, files, and settings. Additionally,
// packageHandles manage a key for these inputs, to use in looking up
// precomputed results.
//
// packageHandles may be invalid following an invalidation via snapshot.clone,
// but the handles returned by getPackageHandles will always be valid.
//
// packageHandles are critical for implementing "precise pruning" in gopls:
// packageHandle.key is a hash of a precise set of inputs, such as package
// files and "reachable" syntax, that may affect type checking.
//
// packageHandles also keep track of state that allows gopls to compute, and
// then quickly recompute, these keys. This state is split into two categories:
// - local state, which depends only on the package's local files and metadata
// - other state, which includes data derived from dependencies.
//
// Dividing the data in this way allows gopls to minimize invalidation when a
// package is modified. For example, any change to a package file fully
// invalidates the package handle. On the other hand, if that change was not
// metadata-affecting it may be the case that packages indirectly depending on
// the modified package are unaffected by the change. For that reason, we have
// two types of invalidation, corresponding to the two types of data above:
// - deletion of the handle, which occurs when the package itself changes
// - clearing of the validated field, which marks the package as possibly
// invalid.
//
// With the second type of invalidation, packageHandles are re-evaluated from the
// bottom up. If this process encounters a packageHandle whose deps have not
// changed (as detected by the depkeys field), then the packageHandle in
// question must also not have changed, and we need not re-evaluate its key.
type packageHandle struct {
mp *metadata.Package
// loadDiagnostics memoizes the result of processing error messages from
// go/packages (i.e. `go list`).
//
// These are derived from metadata using a snapshot. Since they depend on
// file contents (for translating positions), they should theoretically be
// invalidated by file changes, but historically haven't been. In practice
// they are rare and indicate a fundamental error that needs to be corrected
// before development can continue, so it may not be worth significant
// engineering effort to implement accurate invalidation here.
//
// TODO(rfindley): loadDiagnostics are out of place here, as they don't
// directly relate to type checking. We should perhaps move the caching of
// load diagnostics to an entirely separate component, so that Packages need
// only be concerned with parsing and type checking.
// (Nevertheless, since the lifetime of load diagnostics matches that of the
// Metadata, it is convenient to memoize them here.)
loadDiagnostics []*Diagnostic
// Local data:
// localInputs holds all local type-checking localInputs, excluding
// dependencies.
localInputs typeCheckInputs
// localKey is a hash of localInputs.
localKey file.Hash
// refs is the result of syntactic dependency analysis produced by the
// typerefs package.
refs map[string][]typerefs.Symbol
// Data derived from dependencies:
// validated indicates whether the current packageHandle is known to have a
// valid key. Invalidated package handles are stored for packages whose
// type information may have changed.
validated bool
// depKeys records the key of each dependency that was used to calculate the
// key above. If the handle becomes invalid, we must re-check that each still
// matches.
depKeys map[PackageID]file.Hash
// key is the hashed key for the package.
//
// It includes the all bits of the transitive closure of
// dependencies's sources.
key file.Hash
}
// clone returns a copy of the receiver with the validated bit set to the
// provided value.
func (ph *packageHandle) clone(validated bool) *packageHandle {
copy := *ph
copy.validated = validated
return ©
}
// getPackageHandles gets package handles for all given ids and their
// dependencies, recursively.
func (s *Snapshot) getPackageHandles(ctx context.Context, ids []PackageID) (map[PackageID]*packageHandle, error) {
// perform a two-pass traversal.
//
// On the first pass, build up a bidirectional graph of handle nodes, and collect leaves.
// Then build package handles from bottom up.
s.mu.Lock() // guard s.meta and s.packages below
b := &packageHandleBuilder{
s: s,
transitiveRefs: make(map[typerefs.IndexID]*partialRefs),
nodes: make(map[typerefs.IndexID]*handleNode),
}
var leaves []*handleNode
var makeNode func(*handleNode, PackageID) *handleNode
makeNode = func(from *handleNode, id PackageID) *handleNode {
idxID := b.s.pkgIndex.IndexID(id)
n, ok := b.nodes[idxID]
if !ok {
mp := s.meta.Packages[id]
if mp == nil {
panic(fmt.Sprintf("nil metadata for %q", id))
}
n = &handleNode{
mp: mp,
idxID: idxID,
unfinishedSuccs: int32(len(mp.DepsByPkgPath)),
}
if entry, hit := b.s.packages.Get(mp.ID); hit {
n.ph = entry
}
if n.unfinishedSuccs == 0 {
leaves = append(leaves, n)
} else {
n.succs = make(map[PackageID]*handleNode, n.unfinishedSuccs)
}
b.nodes[idxID] = n
for _, depID := range mp.DepsByPkgPath {
n.succs[depID] = makeNode(n, depID)
}
}
// Add edge from predecessor.
if from != nil {
n.preds = append(n.preds, from)
}
return n
}
for _, id := range ids {
makeNode(nil, id)
}
s.mu.Unlock()
g, ctx := errgroup.WithContext(ctx)
// files are preloaded, so building package handles is CPU-bound.
//
// Note that we can't use g.SetLimit, as that could result in starvation:
// g.Go blocks until a slot is available, and so all existing goroutines
// could be blocked trying to enqueue a predecessor.
limiter := make(chan unit, runtime.GOMAXPROCS(0))
var enqueue func(*handleNode)
enqueue = func(n *handleNode) {
g.Go(func() error {
limiter <- unit{}
defer func() { <-limiter }()
if ctx.Err() != nil {
return ctx.Err()
}
b.buildPackageHandle(ctx, n)
for _, pred := range n.preds {
if atomic.AddInt32(&pred.unfinishedSuccs, -1) == 0 {
enqueue(pred)
}
}
return n.err
})
}
for _, leaf := range leaves {
enqueue(leaf)
}
if err := g.Wait(); err != nil {
return nil, err
}
// Copy handles into the result map.
handles := make(map[PackageID]*packageHandle, len(b.nodes))
for _, v := range b.nodes {
assert(v.ph != nil, "nil handle")
handles[v.mp.ID] = v.ph
// debugging #60890
if v.ph.mp.PkgPath == "unsafe" && v.mp.ID != "unsafe" {
bug.Reportf("PackagePath \"unsafe\" with ID %q", v.mp.ID)
}
}
return handles, nil
}
// A packageHandleBuilder computes a batch of packageHandles concurrently,
// sharing computed transitive reachability sets used to compute package keys.
type packageHandleBuilder struct {
s *Snapshot
// nodes are assembled synchronously.
nodes map[typerefs.IndexID]*handleNode
// transitiveRefs is incrementally evaluated as package handles are built.
transitiveRefsMu sync.Mutex
transitiveRefs map[typerefs.IndexID]*partialRefs // see getTransitiveRefs
}
// A handleNode represents a to-be-computed packageHandle within a graph of
// predecessors and successors.
//
// It is used to implement a bottom-up construction of packageHandles.
type handleNode struct {
mp *metadata.Package
idxID typerefs.IndexID
ph *packageHandle
err error
preds []*handleNode
succs map[PackageID]*handleNode
unfinishedSuccs int32
}
// partialRefs maps names declared by a given package to their set of
// transitive references.
//
// If complete is set, refs is known to be complete for the package in
// question. Otherwise, it may only map a subset of all names declared by the
// package.
type partialRefs struct {
refs map[string]*typerefs.PackageSet
complete bool
}
// getTransitiveRefs gets or computes the set of transitively reachable
// packages for each exported name in the package specified by id.
//
// The operation may fail if building a predecessor failed. If and only if this
// occurs, the result will be nil.
func (b *packageHandleBuilder) getTransitiveRefs(pkgID PackageID) map[string]*typerefs.PackageSet {
b.transitiveRefsMu.Lock()
defer b.transitiveRefsMu.Unlock()
idxID := b.s.pkgIndex.IndexID(pkgID)
trefs, ok := b.transitiveRefs[idxID]
if !ok {
trefs = &partialRefs{
refs: make(map[string]*typerefs.PackageSet),
}
b.transitiveRefs[idxID] = trefs
}
if !trefs.complete {
trefs.complete = true
ph := b.nodes[idxID].ph
for name := range ph.refs {
if ('A' <= name[0] && name[0] <= 'Z') || token.IsExported(name) {
if _, ok := trefs.refs[name]; !ok {
pkgs := b.s.pkgIndex.NewSet()
for _, sym := range ph.refs[name] {
pkgs.Add(sym.Package)
otherSet := b.getOneTransitiveRefLocked(sym)
pkgs.Union(otherSet)
}
trefs.refs[name] = pkgs
}
}
}
}
return trefs.refs
}
// getOneTransitiveRefLocked computes the full set packages transitively
// reachable through the given sym reference.
//
// It may return nil if the reference is invalid (i.e. the referenced name does
// not exist).
func (b *packageHandleBuilder) getOneTransitiveRefLocked(sym typerefs.Symbol) *typerefs.PackageSet {
assert(token.IsExported(sym.Name), "expected exported symbol")
trefs := b.transitiveRefs[sym.Package]
if trefs == nil {
trefs = &partialRefs{
refs: make(map[string]*typerefs.PackageSet),
complete: false,
}
b.transitiveRefs[sym.Package] = trefs
}
pkgs, ok := trefs.refs[sym.Name]
if ok && pkgs == nil {
// See below, where refs is set to nil before recursing.
bug.Reportf("cycle detected to %q in reference graph", sym.Name)
}
// Note that if (!ok && trefs.complete), the name does not exist in the
// referenced package, and we should not write to trefs as that may introduce
// a race.
if !ok && !trefs.complete {
n := b.nodes[sym.Package]
if n == nil {
// We should always have IndexID in our node set, because symbol references
// should only be recorded for packages that actually exist in the import graph.
//
// However, it is not easy to prove this (typerefs are serialized and
// deserialized), so make this code temporarily defensive while we are on a
// point release.
//
// TODO(rfindley): in the future, we should turn this into an assertion.
bug.Reportf("missing reference to package %s", b.s.pkgIndex.PackageID(sym.Package))
return nil
}
// Break cycles. This is perhaps overly defensive as cycles should not
// exist at this point: metadata cycles should have been broken at load
// time, and intra-package reference cycles should have been contracted by
// the typerefs algorithm.
//
// See the "cycle detected" bug report above.
trefs.refs[sym.Name] = nil
pkgs := b.s.pkgIndex.NewSet()
for _, sym2 := range n.ph.refs[sym.Name] {
pkgs.Add(sym2.Package)
otherSet := b.getOneTransitiveRefLocked(sym2)
pkgs.Union(otherSet)
}
trefs.refs[sym.Name] = pkgs
}
return pkgs
}
// buildPackageHandle gets or builds a package handle for the given id, storing
// its result in the snapshot.packages map.
//
// buildPackageHandle must only be called from getPackageHandles.
func (b *packageHandleBuilder) buildPackageHandle(ctx context.Context, n *handleNode) {
var prevPH *packageHandle
if n.ph != nil {
// Existing package handle: if it is valid, return it. Otherwise, create a
// copy to update.
if n.ph.validated {
return
}
prevPH = n.ph
// Either prevPH is still valid, or we will update the key and depKeys of
// this copy. In either case, the result will be valid.
n.ph = prevPH.clone(true)
} else {
// No package handle: read and analyze the package syntax.
inputs, err := b.s.typeCheckInputs(ctx, n.mp)
if err != nil {
n.err = err
return
}
refs, err := b.s.typerefs(ctx, n.mp, inputs.compiledGoFiles)
if err != nil {
n.err = err
return
}
n.ph = &packageHandle{
mp: n.mp,
loadDiagnostics: computeLoadDiagnostics(ctx, b.s, n.mp),
localInputs: inputs,
localKey: localPackageKey(inputs),
refs: refs,
validated: true,
}
}
// ph either did not exist, or was invalid. We must re-evaluate deps and key.
if err := b.evaluatePackageHandle(prevPH, n); err != nil {
n.err = err
return
}
assert(n.ph.validated, "unvalidated handle")
// Ensure the result (or an equivalent) is recorded in the snapshot.
b.s.mu.Lock()
defer b.s.mu.Unlock()
// Check that the metadata has not changed
// (which should invalidate this handle).
//
// TODO(rfindley): eventually promote this to an assert.
// TODO(rfindley): move this to after building the package handle graph?
if b.s.meta.Packages[n.mp.ID] != n.mp {
bug.Reportf("stale metadata for %s", n.mp.ID)
}
// Check the packages map again in case another goroutine got there first.
if alt, ok := b.s.packages.Get(n.mp.ID); ok && alt.validated {
if alt.mp != n.mp {
bug.Reportf("existing package handle does not match for %s", n.mp.ID)
}
n.ph = alt
} else {
b.s.packages.Set(n.mp.ID, n.ph, nil)
}
}
// evaluatePackageHandle validates and/or computes the key of ph, setting key,
// depKeys, and the validated flag on ph.
//
// It uses prevPH to avoid recomputing keys that can't have changed, since
// their depKeys did not change.
//
// See the documentation for packageHandle for more details about packageHandle
// state, and see the documentation for the typerefs package for more details
// about precise reachability analysis.
func (b *packageHandleBuilder) evaluatePackageHandle(prevPH *packageHandle, n *handleNode) error {
// Opt: if no dep keys have changed, we need not re-evaluate the key.
if prevPH != nil {
depsChanged := false
assert(len(prevPH.depKeys) == len(n.succs), "mismatching dep count")
for id, succ := range n.succs {
oldKey, ok := prevPH.depKeys[id]
assert(ok, "missing dep")
if oldKey != succ.ph.key {
depsChanged = true
break
}
}
if !depsChanged {
return nil // key cannot have changed
}
}
// Deps have changed, so we must re-evaluate the key.
n.ph.depKeys = make(map[PackageID]file.Hash)
// See the typerefs package: the reachable set of packages is defined to be
// the set of packages containing syntax that is reachable through the
// exported symbols in the dependencies of n.ph.
reachable := b.s.pkgIndex.NewSet()
for depID, succ := range n.succs {
n.ph.depKeys[depID] = succ.ph.key
reachable.Add(succ.idxID)
trefs := b.getTransitiveRefs(succ.mp.ID)
if trefs == nil {
// A predecessor failed to build due to e.g. context cancellation.
return fmt.Errorf("missing transitive refs for %s", succ.mp.ID)
}
for _, set := range trefs {
reachable.Union(set)
}
}
// Collect reachable handles.
var reachableHandles []*packageHandle
// In the presence of context cancellation, any package may be missing.
// We need all dependencies to produce a valid key.
missingReachablePackage := false
reachable.Elems(func(id typerefs.IndexID) {
dh := b.nodes[id]
if dh == nil {
missingReachablePackage = true
} else {
assert(dh.ph.validated, "unvalidated dependency")
reachableHandles = append(reachableHandles, dh.ph)
}
})
if missingReachablePackage {
return fmt.Errorf("missing reachable package")
}
// Sort for stability.
sort.Slice(reachableHandles, func(i, j int) bool {
return reachableHandles[i].mp.ID < reachableHandles[j].mp.ID
})
// Key is the hash of the local key, and the local key of all reachable
// packages.
depHasher := sha256.New()
depHasher.Write(n.ph.localKey[:])
for _, rph := range reachableHandles {
depHasher.Write(rph.localKey[:])
}
depHasher.Sum(n.ph.key[:0])
return nil
}
// typerefs returns typerefs for the package described by m and cgfs, after
// either computing it or loading it from the file cache.
func (s *Snapshot) typerefs(ctx context.Context, mp *metadata.Package, cgfs []file.Handle) (map[string][]typerefs.Symbol, error) {
imports := make(map[ImportPath]*metadata.Package)
for impPath, id := range mp.DepsByImpPath {
if id != "" {
imports[impPath] = s.Metadata(id)
}
}
data, err := s.typerefData(ctx, mp.ID, imports, cgfs)
if err != nil {
return nil, err
}
classes := typerefs.Decode(s.pkgIndex, data)
refs := make(map[string][]typerefs.Symbol)
for _, class := range classes {
for _, decl := range class.Decls {
refs[decl] = class.Refs
}
}
return refs, nil
}
// typerefData retrieves encoded typeref data from the filecache, or computes it on
// a cache miss.
func (s *Snapshot) typerefData(ctx context.Context, id PackageID, imports map[ImportPath]*metadata.Package, cgfs []file.Handle) ([]byte, error) {
key := typerefsKey(id, imports, cgfs)
if data, err := filecache.Get(typerefsKind, key); err == nil {
return data, nil
} else if err != filecache.ErrNotFound {
bug.Reportf("internal error reading typerefs data: %v", err)
}
pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), parsego.Full&^parser.ParseComments, true, cgfs...)
if err != nil {
return nil, err
}
data := typerefs.Encode(pgfs, imports)
// Store the resulting data in the cache.
go func() {
if err := filecache.Set(typerefsKind, key, data); err != nil {
event.Error(ctx, fmt.Sprintf("storing typerefs data for %s", id), err)
}
}()
return data, nil
}
// typerefsKey produces a key for the reference information produced by the
// typerefs package.
func typerefsKey(id PackageID, imports map[ImportPath]*metadata.Package, compiledGoFiles []file.Handle) file.Hash {
hasher := sha256.New()
fmt.Fprintf(hasher, "typerefs: %s\n", id)
importPaths := make([]string, 0, len(imports))
for impPath := range imports {
importPaths = append(importPaths, string(impPath))
}
sort.Strings(importPaths)
for _, importPath := range importPaths {
imp := imports[ImportPath(importPath)]
// TODO(rfindley): strength reduce the typerefs.Export API to guarantee
// that it only depends on these attributes of dependencies.
fmt.Fprintf(hasher, "import %s %s %s", importPath, imp.ID, imp.Name)
}
fmt.Fprintf(hasher, "compiledGoFiles: %d\n", len(compiledGoFiles))
for _, fh := range compiledGoFiles {
fmt.Fprintln(hasher, fh.Identity())
}
var hash [sha256.Size]byte
hasher.Sum(hash[:0])
return hash
}
// typeCheckInputs contains the inputs of a call to typeCheckImpl, which
// type-checks a package.
//
// Part of the purpose of this type is to keep type checking in-sync with the
// package handle key, by explicitly identifying the inputs to type checking.
type typeCheckInputs struct {
id PackageID
// Used for type checking:
pkgPath PackagePath
name PackageName
goFiles, compiledGoFiles []file.Handle
sizes types.Sizes
depsByImpPath map[ImportPath]PackageID
goVersion string // packages.Module.GoVersion, e.g. "1.18"
// Used for type check diagnostics:
// TODO(rfindley): consider storing less data in gobDiagnostics, and
// interpreting each diagnostic in the context of a fixed set of options.
// Then these fields need not be part of the type checking inputs.
supportsRelatedInformation bool
linkTarget string
viewType ViewType
}
func (s *Snapshot) typeCheckInputs(ctx context.Context, mp *metadata.Package) (typeCheckInputs, error) {
// Read both lists of files of this package.
//
// Parallelism is not necessary here as the files will have already been
// pre-read at load time.
//
// goFiles aren't presented to the type checker--nor
// are they included in the key, unsoundly--but their
// syntax trees are available from (*pkg).File(URI).
// TODO(adonovan): consider parsing them on demand?
// The need should be rare.
goFiles, err := readFiles(ctx, s, mp.GoFiles)
if err != nil {
return typeCheckInputs{}, err
}
compiledGoFiles, err := readFiles(ctx, s, mp.CompiledGoFiles)
if err != nil {
return typeCheckInputs{}, err
}
goVersion := ""
if mp.Module != nil && mp.Module.GoVersion != "" {
goVersion = mp.Module.GoVersion
}
return typeCheckInputs{
id: mp.ID,
pkgPath: mp.PkgPath,
name: mp.Name,
goFiles: goFiles,
compiledGoFiles: compiledGoFiles,
sizes: mp.TypesSizes,
depsByImpPath: mp.DepsByImpPath,
goVersion: goVersion,
supportsRelatedInformation: s.Options().RelatedInformationSupported,
linkTarget: s.Options().LinkTarget,
viewType: s.view.typ,
}, nil
}
// readFiles reads the content of each file URL from the source
// (e.g. snapshot or cache).
func readFiles(ctx context.Context, fs file.Source, uris []protocol.DocumentURI) (_ []file.Handle, err error) {
fhs := make([]file.Handle, len(uris))
for i, uri := range uris {
fhs[i], err = fs.ReadFile(ctx, uri)
if err != nil {
return nil, err
}
}
return fhs, nil
}
// localPackageKey returns a key for local inputs into type-checking, excluding
// dependency information: files, metadata, and configuration.
func localPackageKey(inputs typeCheckInputs) file.Hash {
hasher := sha256.New()
// In principle, a key must be the hash of an
// unambiguous encoding of all the relevant data.
// If it's ambiguous, we risk collisions.
// package identifiers
fmt.Fprintf(hasher, "package: %s %s %s\n", inputs.id, inputs.name, inputs.pkgPath)
// module Go version
fmt.Fprintf(hasher, "go %s\n", inputs.goVersion)
// import map
importPaths := make([]string, 0, len(inputs.depsByImpPath))
for impPath := range inputs.depsByImpPath {
importPaths = append(importPaths, string(impPath))
}
sort.Strings(importPaths)
for _, impPath := range importPaths {
fmt.Fprintf(hasher, "import %s %s", impPath, string(inputs.depsByImpPath[ImportPath(impPath)]))
}
// file names and contents
fmt.Fprintf(hasher, "compiledGoFiles: %d\n", len(inputs.compiledGoFiles))
for _, fh := range inputs.compiledGoFiles {
fmt.Fprintln(hasher, fh.Identity())
}
fmt.Fprintf(hasher, "goFiles: %d\n", len(inputs.goFiles))
for _, fh := range inputs.goFiles {
fmt.Fprintln(hasher, fh.Identity())
}
// types sizes
wordSize := inputs.sizes.Sizeof(types.Typ[types.Int])
maxAlign := inputs.sizes.Alignof(types.NewPointer(types.Typ[types.Int64]))
fmt.Fprintf(hasher, "sizes: %d %d\n", wordSize, maxAlign)
fmt.Fprintf(hasher, "relatedInformation: %t\n", inputs.supportsRelatedInformation)
fmt.Fprintf(hasher, "linkTarget: %s\n", inputs.linkTarget)
fmt.Fprintf(hasher, "viewType: %d\n", inputs.viewType)
var hash [sha256.Size]byte
hasher.Sum(hash[:0])
return hash
}
// checkPackage type checks the parsed source files in compiledGoFiles.
// (The resulting pkg also holds the parsed but not type-checked goFiles.)
// deps holds the future results of type-checking the direct dependencies.
func (b *typeCheckBatch) checkPackage(ctx context.Context, ph *packageHandle) (*Package, error) {
inputs := ph.localInputs
ctx, done := event.Start(ctx, "cache.typeCheckBatch.checkPackage", label.Package.Of(string(inputs.id)))
defer done()
pkg := &syntaxPackage{
id: inputs.id,
fset: b.fset, // must match parse call below
types: types.NewPackage(string(inputs.pkgPath), string(inputs.name)),
typesSizes: inputs.sizes,
typesInfo: &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Implicits: make(map[ast.Node]types.Object),
Instances: make(map[*ast.Ident]types.Instance),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
Scopes: make(map[ast.Node]*types.Scope),
},
}
versions.InitFileVersions(pkg.typesInfo)
// Collect parsed files from the type check pass, capturing parse errors from
// compiled files.
var err error
pkg.goFiles, err = b.parseCache.parseFiles(ctx, b.fset, parsego.Full, false, inputs.goFiles...)
if err != nil {
return nil, err
}
pkg.compiledGoFiles, err = b.parseCache.parseFiles(ctx, b.fset, parsego.Full, false, inputs.compiledGoFiles...)
if err != nil {
return nil, err
}
for _, pgf := range pkg.compiledGoFiles {
if pgf.ParseErr != nil {
pkg.parseErrors = append(pkg.parseErrors, pgf.ParseErr)
}
}
// Use the default type information for the unsafe package.
if inputs.pkgPath == "unsafe" {
// Don't type check Unsafe: it's unnecessary, and doing so exposes a data
// race to Unsafe.completed.
pkg.types = types.Unsafe
} else {
if len(pkg.compiledGoFiles) == 0 {
// No files most likely means go/packages failed.
//
// TODO(rfindley): in the past, we would capture go list errors in this
// case, to present go list errors to the user. However we had no tests for
// this behavior. It is unclear if anything better can be done here.
return nil, fmt.Errorf("no parsed files for package %s", inputs.pkgPath)
}
onError := func(e error) {
pkg.typeErrors = append(pkg.typeErrors, e.(types.Error))
}
cfg := b.typesConfig(ctx, inputs, onError)
check := types.NewChecker(cfg, pkg.fset, pkg.types, pkg.typesInfo)
var files []*ast.File
for _, cgf := range pkg.compiledGoFiles {
files = append(files, cgf.File)
}
// Type checking is expensive, and we may not have encountered cancellations
// via parsing (e.g. if we got nothing but cache hits for parsed files).
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Type checking errors are handled via the config, so ignore them here.
_ = check.Files(files) // 50us-15ms, depending on size of package
// If the context was cancelled, we may have returned a ton of transient
// errors to the type checker. Swallow them.
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Collect imports by package path for the DependencyTypes API.
pkg.importMap = make(map[PackagePath]*types.Package)
var collectDeps func(*types.Package)
collectDeps = func(p *types.Package) {
pkgPath := PackagePath(p.Path())
if _, ok := pkg.importMap[pkgPath]; ok {
return
}
pkg.importMap[pkgPath] = p
for _, imp := range p.Imports() {
collectDeps(imp)
}
}
collectDeps(pkg.types)
// Work around golang/go#61561: interface instances aren't concurrency-safe
// as they are not completed by the type checker.
for _, inst := range pkg.typesInfo.Instances {
if iface, _ := inst.Type.Underlying().(*types.Interface); iface != nil {
iface.Complete()
}
}
}
// Our heuristic for whether to show type checking errors is:
// + If there is a parse error _in the current file_, suppress type
// errors in that file.
// + Otherwise, show type errors even in the presence of parse errors in
// other package files. go/types attempts to suppress follow-on errors
// due to bad syntax, so on balance type checking errors still provide
// a decent signal/noise ratio as long as the file in question parses.
// Track URIs with parse errors so that we can suppress type errors for these
// files.
unparseable := map[protocol.DocumentURI]bool{}
for _, e := range pkg.parseErrors {
diags, err := parseErrorDiagnostics(pkg, e)
if err != nil {
event.Error(ctx, "unable to compute positions for parse errors", err, label.Package.Of(string(inputs.id)))
continue
}
for _, diag := range diags {
unparseable[diag.URI] = true
pkg.diagnostics = append(pkg.diagnostics, diag)
}
}
diags := typeErrorsToDiagnostics(pkg, inputs, pkg.typeErrors)
for _, diag := range diags {
// If the file didn't parse cleanly, it is highly likely that type
// checking errors will be confusing or redundant. But otherwise, type
// checking usually provides a good enough signal to include.
if !unparseable[diag.URI] {
pkg.diagnostics = append(pkg.diagnostics, diag)
}
}
return &Package{ph.mp, ph.loadDiagnostics, pkg}, nil
}
// e.g. "go1" or "go1.2" or "go1.2.3"
var goVersionRx = regexp.MustCompile(`^go[1-9][0-9]*(?:\.(0|[1-9][0-9]*)){0,2}$`)
func (b *typeCheckBatch) typesConfig(ctx context.Context, inputs typeCheckInputs, onError func(e error)) *types.Config {
cfg := &types.Config{
Sizes: inputs.sizes,
Error: onError,
Importer: importerFunc(func(path string) (*types.Package, error) {
// While all of the import errors could be reported
// based on the metadata before we start type checking,
// reporting them via types.Importer places the errors
// at the correct source location.
id, ok := inputs.depsByImpPath[ImportPath(path)]
if !ok {
// If the import declaration is broken,
// go list may fail to report metadata about it.
// See TestFixImportDecl for an example.
return nil, fmt.Errorf("missing metadata for import of %q", path)
}
depPH := b.handles[id]
if depPH == nil {
// e.g. missing metadata for dependencies in buildPackageHandle
return nil, missingPkgError(inputs.id, path, inputs.viewType)
}
if !metadata.IsValidImport(inputs.pkgPath, depPH.mp.PkgPath, inputs.viewType != GoPackagesDriverView) {
return nil, fmt.Errorf("invalid use of internal package %q", path)
}
return b.getImportPackage(ctx, id)
}),
}
if inputs.goVersion != "" {
goVersion := "go" + inputs.goVersion
if validGoVersion(goVersion) {
cfg.GoVersion = goVersion
}
}
// We want to type check cgo code if go/types supports it.
// We passed typecheckCgo to go/packages when we Loaded.
typesinternal.SetUsesCgo(cfg)
return cfg
}
// validGoVersion reports whether goVersion is a valid Go version for go/types.
// types.NewChecker panics if GoVersion is invalid.
//
// Note that, prior to go1.21, go/types required exactly two components to the
// version number. For example, go types would panic with the Go version
// go1.21.1. validGoVersion handles this case when built with go1.20 or earlier.
func validGoVersion(goVersion string) bool {
if !goVersionRx.MatchString(goVersion) {
return false // malformed version string
}
if relVer := releaseVersion(); relVer != "" && versions.Before(versions.Lang(relVer), versions.Lang(goVersion)) {
return false // 'go list' is too new for go/types
}
// TODO(rfindley): remove once we no longer support building gopls with Go
// 1.20 or earlier.
if !slices.Contains(build.Default.ReleaseTags, "go1.21") && strings.Count(goVersion, ".") >= 2 {
return false // unsupported patch version
}
return true
}
// releaseVersion reports the Go language version used to compile gopls, or ""
// if it cannot be determined.
func releaseVersion() string {
if len(build.Default.ReleaseTags) > 0 {
v := build.Default.ReleaseTags[len(build.Default.ReleaseTags)-1]
var dummy int
if _, err := fmt.Sscanf(v, "go1.%d", &dummy); err == nil {
return v
}
}
return ""
}
// depsErrors creates diagnostics for each metadata error (e.g. import cycle).
// These may be attached to import declarations in the transitive source files
// of pkg, or to 'requires' declarations in the package's go.mod file.
//
// TODO(rfindley): move this to load.go
func depsErrors(ctx context.Context, snapshot *Snapshot, mp *metadata.Package) ([]*Diagnostic, error) {
// Select packages that can't be found, and were imported in non-workspace packages.
// Workspace packages already show their own errors.
var relevantErrors []*packagesinternal.PackageError
for _, depsError := range mp.DepsErrors {
// Up to Go 1.15, the missing package was included in the stack, which
// was presumably a bug. We want the next one up.
directImporterIdx := len(depsError.ImportStack) - 1
if directImporterIdx < 0 {
continue
}
directImporter := depsError.ImportStack[directImporterIdx]
if snapshot.isWorkspacePackage(PackageID(directImporter)) {
continue
}
relevantErrors = append(relevantErrors, depsError)
}
// Don't build the import index for nothing.
if len(relevantErrors) == 0 {
return nil, nil
}
// Subsequent checks require Go files.
if len(mp.CompiledGoFiles) == 0 {
return nil, nil
}
// Build an index of all imports in the package.
type fileImport struct {
cgf *parsego.File
imp *ast.ImportSpec
}
allImports := map[string][]fileImport{}
for _, uri := range mp.CompiledGoFiles {
pgf, err := parseGoURI(ctx, snapshot, uri, parsego.Header)
if err != nil {
return nil, err
}
fset := tokeninternal.FileSetFor(pgf.Tok)
// TODO(adonovan): modify Imports() to accept a single token.File (cgf.Tok).
for _, group := range astutil.Imports(fset, pgf.File) {
for _, imp := range group {
if imp.Path == nil {
continue
}
path := strings.Trim(imp.Path.Value, `"`)
allImports[path] = append(allImports[path], fileImport{pgf, imp})
}
}
}
// Apply a diagnostic to any import involved in the error, stopping once
// we reach the workspace.
var errors []*Diagnostic
for _, depErr := range relevantErrors {
for i := len(depErr.ImportStack) - 1; i >= 0; i-- {
item := depErr.ImportStack[i]
if snapshot.isWorkspacePackage(PackageID(item)) {
break
}
for _, imp := range allImports[item] {
rng, err := imp.cgf.NodeRange(imp.imp)
if err != nil {
return nil, err
}
diag := &Diagnostic{
URI: imp.cgf.URI,
Range: rng,
Severity: protocol.SeverityError,
Source: TypeError,
Message: fmt.Sprintf("error while importing %v: %v", item, depErr.Err),
SuggestedFixes: goGetQuickFixes(mp.Module != nil, imp.cgf.URI, item),
}
if !bundleLazyFixes(diag) {
bug.Reportf("failed to bundle fixes for diagnostic %q", diag.Message)
}
errors = append(errors, diag)
}
}
}
modFile, err := nearestModFile(ctx, mp.CompiledGoFiles[0], snapshot)
if err != nil {
return nil, err
}
pm, err := parseModURI(ctx, snapshot, modFile)
if err != nil {
return nil, err
}
// Add a diagnostic to the module that contained the lowest-level import of
// the missing package.
for _, depErr := range relevantErrors {
for i := len(depErr.ImportStack) - 1; i >= 0; i-- {
item := depErr.ImportStack[i]
mp := snapshot.Metadata(PackageID(item))
if mp == nil || mp.Module == nil {
continue
}
modVer := module.Version{Path: mp.Module.Path, Version: mp.Module.Version}
reference := findModuleReference(pm.File, modVer)
if reference == nil {
continue
}
rng, err := pm.Mapper.OffsetRange(reference.Start.Byte, reference.End.Byte)
if err != nil {
return nil, err
}
diag := &Diagnostic{
URI: pm.URI,
Range: rng,
Severity: protocol.SeverityError,
Source: TypeError,
Message: fmt.Sprintf("error while importing %v: %v", item, depErr.Err),
SuggestedFixes: goGetQuickFixes(true, pm.URI, item),
}
if !bundleLazyFixes(diag) {
bug.Reportf("failed to bundle fixes for diagnostic %q", diag.Message)
}
errors = append(errors, diag)
break
}
}
return errors, nil
}
// missingPkgError returns an error message for a missing package that varies
// based on the user's workspace mode.
func missingPkgError(from PackageID, pkgPath string, viewType ViewType) error {
switch viewType {
case GoModView, GoWorkView:
if metadata.IsCommandLineArguments(from) {
return fmt.Errorf("current file is not included in a workspace module")
} else {
// Previously, we would present the initialization error here.
return fmt.Errorf("no required module provides package %q", pkgPath)
}
case AdHocView:
return fmt.Errorf("cannot find package %q in GOROOT", pkgPath)
case GoPackagesDriverView:
return fmt.Errorf("go/packages driver could not load %q", pkgPath)
case GOPATHView:
return fmt.Errorf("cannot find package %q in GOROOT or GOPATH", pkgPath)
default:
return fmt.Errorf("unable to load package")
}
}
// typeErrorsToDiagnostics translates a slice of types.Errors into a slice of
// Diagnostics.
//
// In addition to simply mapping data such as position information and error
// codes, this function interprets related go/types "continuation" errors as
// protocol.DiagnosticRelatedInformation. Continuation errors are go/types
// errors whose messages starts with "\t". By convention, these errors relate
// to the previous error in the errs slice (such as if they were printed in
// sequence to a terminal).
//
// Fields in typeCheckInputs may affect the resulting diagnostics.
func typeErrorsToDiagnostics(pkg *syntaxPackage, inputs typeCheckInputs, errs []types.Error) []*Diagnostic {
var result []*Diagnostic
// batch records diagnostics for a set of related types.Errors.
// (related[0] is the primary error.)
batch := func(related []types.Error) {
var diags []*Diagnostic
for i, e := range related {
code, start, end, ok := typesinternal.ReadGo116ErrorData(e)
if !ok || !start.IsValid() || !end.IsValid() {
start, end = e.Pos, e.Pos
code = 0
}
if !start.IsValid() {
// Type checker errors may be missing position information if they
// relate to synthetic syntax, such as if the file were fixed. In that
// case, we should have a parse error anyway, so skipping the type
// checker error is likely benign.
//
// TODO(golang/go#64335): we should eventually verify that all type
// checked syntax has valid positions, and promote this skip to a bug
// report.
continue
}
// Invariant: both start and end are IsValid.
if !end.IsValid() {
panic("end is invalid")
}
posn := safetoken.StartPosition(e.Fset, start)
if !posn.IsValid() {
// All valid positions produced by the type checker should described by
// its fileset.
//
// Note: in golang/go#64488, we observed an error that was positioned
// over fixed syntax, which overflowed its file. So it's definitely
// possible that we get here (it's hard to reason about fixing up the
// AST). Nevertheless, it's a bug.
bug.Reportf("internal error: type checker error %q outside its Fset", e)
continue
}
pgf, err := pkg.File(protocol.URIFromPath(posn.Filename))
if err != nil {
// Sometimes type-checker errors refer to positions in other packages,
// such as when a declaration duplicates a dot-imported name.
//
// In these cases, we don't want to report an error in the other
// package (the message would be rather confusing), but we do want to
// report an error in the current package (golang/go#59005).
if i == 0 {
bug.Reportf("internal error: could not locate file for primary type checker error %v: %v", e, err)
}
continue
}
// debugging #65960
//
// At this point, we know 'start' IsValid, and
// StartPosition(start) worked (with e.Fset).
//
// If the asserted condition is true, 'start'
// is also in range for pgf.Tok, which means
// the PosRange failure must be caused by 'end'.
if pgf.Tok != e.Fset.File(start) {
bug.Reportf("internal error: inconsistent token.Files for pos")
}
if end == start {
// Expand the end position to a more meaningful span.
end = analysisinternal.TypeErrorEndPos(e.Fset, pgf.Src, start)
// debugging #65960
if _, err := safetoken.Offset(pgf.Tok, end); err != nil {
bug.Reportf("TypeErrorEndPos returned invalid end: %v", err)
}
} else {
// debugging #65960
if _, err := safetoken.Offset(pgf.Tok, end); err != nil {
bug.Reportf("ReadGo116ErrorData returned invalid end: %v", err)
}
}
rng, err := pgf.Mapper.PosRange(pgf.Tok, start, end)
if err != nil {
bug.Reportf("internal error: could not compute pos to range for %v: %v", e, err)
continue
}
msg := related[0].Msg // primary
if i > 0 {
if inputs.supportsRelatedInformation {
msg += " (see details)"
} else {
msg += fmt.Sprintf(" (this error: %v)", e.Msg)
}
}
diag := &Diagnostic{
URI: pgf.URI,
Range: rng,
Severity: protocol.SeverityError,
Source: TypeError,
Message: msg,
}
if code != 0 {
diag.Code = code.String()
diag.CodeHref = typesCodeHref(inputs.linkTarget, code)
}
if code == typesinternal.UnusedVar || code == typesinternal.UnusedImport {
diag.Tags = append(diag.Tags, protocol.Unnecessary)
}
if match := importErrorRe.FindStringSubmatch(e.Msg); match != nil {
diag.SuggestedFixes = append(diag.SuggestedFixes, goGetQuickFixes(inputs.viewType.usesModules(), pgf.URI, match[1])...)
}
if match := unsupportedFeatureRe.FindStringSubmatch(e.Msg); match != nil {
diag.SuggestedFixes = append(diag.SuggestedFixes, editGoDirectiveQuickFix(inputs.viewType.usesModules(), pgf.URI, match[1])...)
}
// Link up related information. For the primary error, all related errors
// are treated as related information. For secondary errors, only the
// primary is related.
//
// This is because go/types assumes that errors are read top-down, such as
// in the cycle error "A refers to...". The structure of the secondary
// error set likely only makes sense for the primary error.
//
// NOTE: len(diags) == 0 if the primary diagnostic has invalid positions.
// See also golang/go#66731.
if i > 0 && len(diags) > 0 {
primary := diags[0]
primary.Related = append(primary.Related, protocol.DiagnosticRelatedInformation{
Location: protocol.Location{URI: diag.URI, Range: diag.Range},
Message: related[i].Msg, // use the unmodified secondary error for related errors.
})
diag.Related = []protocol.DiagnosticRelatedInformation{{
Location: protocol.Location{URI: primary.URI, Range: primary.Range},
}}
}
diags = append(diags, diag)
}
result = append(result, diags...)
}
// Process batches of related errors.
for len(errs) > 0 {
related := []types.Error{errs[0]}
for i := 1; i < len(errs); i++ {
spl := errs[i]
if len(spl.Msg) == 0 || spl.Msg[0] != '\t' {
break
}
spl.Msg = spl.Msg[len("\t"):]
related = append(related, spl)
}
batch(related)
errs = errs[len(related):]
}
return result
}
// An importFunc is an implementation of the single-method
// types.Importer interface based on a function value.
type importerFunc func(path string) (*types.Package, error)
func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
| tools/gopls/internal/cache/check.go/0 | {
"file_path": "tools/gopls/internal/cache/check.go",
"repo_id": "tools",
"token_count": 23974
} | 730 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package metadata
import (
"sort"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/util/bug"
)
// A Graph is an immutable and transitively closed graph of [Package] data.
type Graph struct {
// Packages maps package IDs to their associated Packages.
Packages map[PackageID]*Package
// ImportedBy maps package IDs to the list of packages that import them.
ImportedBy map[PackageID][]PackageID
// IDs maps file URIs to package IDs, sorted by (!valid, cli, packageID).
// A single file may belong to multiple packages due to tests packages.
//
// Invariant: all IDs present in the IDs map exist in the metadata map.
IDs map[protocol.DocumentURI][]PackageID
}
// Update creates a new Graph containing the result of applying the given
// updates to the receiver, though the receiver is not itself mutated. As a
// special case, if updates is empty, Update just returns the receiver.
//
// A nil map value is used to indicate a deletion.
func (g *Graph) Update(updates map[PackageID]*Package) *Graph {
if len(updates) == 0 {
// Optimization: since the graph is immutable, we can return the receiver.
return g
}
// Debugging golang/go#64227, golang/vscode-go#3126:
// Assert that the existing metadata graph is acyclic.
if cycle := cyclic(g.Packages); cycle != "" {
bug.Reportf("metadata is cyclic even before updates: %s", cycle)
}
// Assert that the updates contain no self-cycles.
for id, mp := range updates {
if mp != nil {
for _, depID := range mp.DepsByPkgPath {
if depID == id {
bug.Reportf("self-cycle in metadata update: %s", id)
}
}
}
}
// Copy pkgs map then apply updates.
pkgs := make(map[PackageID]*Package, len(g.Packages))
for id, mp := range g.Packages {
pkgs[id] = mp
}
for id, mp := range updates {
if mp == nil {
delete(pkgs, id)
} else {
pkgs[id] = mp
}
}
// Break import cycles involving updated nodes.
breakImportCycles(pkgs, updates)
return newGraph(pkgs)
}
// newGraph returns a new metadataGraph,
// deriving relations from the specified metadata.
func newGraph(pkgs map[PackageID]*Package) *Graph {
// Build the import graph.
importedBy := make(map[PackageID][]PackageID)
for id, mp := range pkgs {
for _, depID := range mp.DepsByPkgPath {
importedBy[depID] = append(importedBy[depID], id)
}
}
// Collect file associations.
uriIDs := make(map[protocol.DocumentURI][]PackageID)
for id, mp := range pkgs {
uris := map[protocol.DocumentURI]struct{}{}
for _, uri := range mp.CompiledGoFiles {
uris[uri] = struct{}{}
}
for _, uri := range mp.GoFiles {
uris[uri] = struct{}{}
}
for uri := range uris {
uriIDs[uri] = append(uriIDs[uri], id)
}
}
// Sort and filter file associations.
for uri, ids := range uriIDs {
sort.Slice(ids, func(i, j int) bool {
cli := IsCommandLineArguments(ids[i])
clj := IsCommandLineArguments(ids[j])
if cli != clj {
return clj
}
// 2. packages appear in name order.
return ids[i] < ids[j]
})
// Choose the best IDs for each URI, according to the following rules:
// - If there are any valid real packages, choose them.
// - Else, choose the first valid command-line-argument package, if it exists.
//
// TODO(rfindley): it might be better to track all IDs here, and exclude
// them later when type checking, but this is the existing behavior.
for i, id := range ids {
// If we've seen *anything* prior to command-line arguments package, take
// it. Note that ids[0] may itself be command-line-arguments.
if i > 0 && IsCommandLineArguments(id) {
uriIDs[uri] = ids[:i]
break
}
}
}
return &Graph{
Packages: pkgs,
ImportedBy: importedBy,
IDs: uriIDs,
}
}
// ReverseReflexiveTransitiveClosure returns a new mapping containing the
// metadata for the specified packages along with any package that
// transitively imports one of them, keyed by ID, including all the initial packages.
func (g *Graph) ReverseReflexiveTransitiveClosure(ids ...PackageID) map[PackageID]*Package {
seen := make(map[PackageID]*Package)
var visitAll func([]PackageID)
visitAll = func(ids []PackageID) {
for _, id := range ids {
if seen[id] == nil {
if mp := g.Packages[id]; mp != nil {
seen[id] = mp
visitAll(g.ImportedBy[id])
}
}
}
}
visitAll(ids)
return seen
}
// breakImportCycles breaks import cycles in the metadata by deleting
// Deps* edges. It modifies only metadata present in the 'updates'
// subset. This function has an internal test.
func breakImportCycles(metadata, updates map[PackageID]*Package) {
// 'go list' should never report a cycle without flagging it
// as such, but we're extra cautious since we're combining
// information from multiple runs of 'go list'. Also, Bazel
// may silently report cycles.
cycles := detectImportCycles(metadata, updates)
if len(cycles) > 0 {
// There were cycles (uncommon). Break them.
//
// The naive way to break cycles would be to perform a
// depth-first traversal and to detect and delete
// cycle-forming edges as we encounter them.
// However, we're not allowed to modify the existing
// Metadata records, so we can only break edges out of
// the 'updates' subset.
//
// Another possibility would be to delete not the
// cycle forming edge but the topmost edge on the
// stack whose tail is an updated node.
// However, this would require that we retroactively
// undo all the effects of the traversals that
// occurred since that edge was pushed on the stack.
//
// We use a simpler scheme: we compute the set of cycles.
// All cyclic paths necessarily involve at least one
// updated node, so it is sufficient to break all
// edges from each updated node to other members of
// the strong component.
//
// This may result in the deletion of dominating
// edges, causing some dependencies to appear
// spuriously unreachable. Consider A <-> B -> C
// where updates={A,B}. The cycle is {A,B} so the
// algorithm will break both A->B and B->A, causing
// A to no longer depend on B or C.
//
// But that's ok: any error in Metadata.Errors is
// conservatively assumed by snapshot.clone to be a
// potential import cycle error, and causes special
// invalidation so that if B later drops its
// cycle-forming import of A, both A and B will be
// invalidated.
for _, cycle := range cycles {
cyclic := make(map[PackageID]bool)
for _, mp := range cycle {
cyclic[mp.ID] = true
}
for id := range cyclic {
if mp := updates[id]; mp != nil {
for path, depID := range mp.DepsByImpPath {
if cyclic[depID] {
delete(mp.DepsByImpPath, path)
}
}
for path, depID := range mp.DepsByPkgPath {
if cyclic[depID] {
delete(mp.DepsByPkgPath, path)
}
}
// Set m.Errors to enable special
// invalidation logic in snapshot.clone.
if len(mp.Errors) == 0 {
mp.Errors = []packages.Error{{
Msg: "detected import cycle",
Kind: packages.ListError,
}}
}
}
}
}
// double-check when debugging
if false {
if cycles := detectImportCycles(metadata, updates); len(cycles) > 0 {
bug.Reportf("unbroken cycle: %v", cycles)
}
}
}
}
// cyclic returns a description of a cycle,
// if the graph is cyclic, otherwise "".
func cyclic(graph map[PackageID]*Package) string {
const (
unvisited = 0
visited = 1
onstack = 2
)
color := make(map[PackageID]int)
var visit func(id PackageID) string
visit = func(id PackageID) string {
switch color[id] {
case unvisited:
color[id] = onstack
case onstack:
return string(id) // cycle!
case visited:
return ""
}
if mp := graph[id]; mp != nil {
for _, depID := range mp.DepsByPkgPath {
if cycle := visit(depID); cycle != "" {
return string(id) + "->" + cycle
}
}
}
color[id] = visited
return ""
}
for id := range graph {
if cycle := visit(id); cycle != "" {
return cycle
}
}
return ""
}
// detectImportCycles reports cycles in the metadata graph. It returns a new
// unordered array of all cycles (nontrivial strong components) in the
// metadata graph reachable from a non-nil 'updates' value.
func detectImportCycles(metadata, updates map[PackageID]*Package) [][]*Package {
// We use the depth-first algorithm of Tarjan.
// https://doi.org/10.1137/0201010
//
// TODO(adonovan): when we can use generics, consider factoring
// in common with the other implementation of Tarjan (in typerefs),
// abstracting over the node and edge representation.
// A node wraps a Metadata with its working state.
// (Unfortunately we can't intrude on shared Metadata.)
type node struct {
rep *node
mp *Package
index, lowlink int32
scc int8 // TODO(adonovan): opt: cram these 1.5 bits into previous word
}
nodes := make(map[PackageID]*node, len(metadata))
nodeOf := func(id PackageID) *node {
n, ok := nodes[id]
if !ok {
mp := metadata[id]
if mp == nil {
// Dangling import edge.
// Not sure whether a go/packages driver ever
// emits this, but create a dummy node in case.
// Obviously it won't be part of any cycle.
mp = &Package{ID: id}
}
n = &node{mp: mp}
n.rep = n
nodes[id] = n
}
return n
}
// find returns the canonical node decl.
// (The nodes form a disjoint set forest.)
var find func(*node) *node
find = func(n *node) *node {
rep := n.rep
if rep != n {
rep = find(rep)
n.rep = rep // simple path compression (no union-by-rank)
}
return rep
}
// global state
var (
index int32 = 1
stack []*node
sccs [][]*Package // set of nontrivial strongly connected components
)
// visit implements the depth-first search of Tarjan's SCC algorithm
// Precondition: x is canonical.
var visit func(*node)
visit = func(x *node) {
x.index = index
x.lowlink = index
index++
stack = append(stack, x) // push
x.scc = -1
for _, yid := range x.mp.DepsByPkgPath {
y := nodeOf(yid)
// Loop invariant: x is canonical.
y = find(y)
if x == y {
continue // nodes already combined (self-edges are impossible)
}
switch {
case y.scc > 0:
// y is already a collapsed SCC
case y.scc < 0:
// y is on the stack, and thus in the current SCC.
if y.index < x.lowlink {
x.lowlink = y.index
}
default:
// y is unvisited; visit it now.
visit(y)
// Note: x and y are now non-canonical.
x = find(x)
if y.lowlink < x.lowlink {
x.lowlink = y.lowlink
}
}
}
// Is x the root of an SCC?
if x.lowlink == x.index {
// Gather all metadata in the SCC (if nontrivial).
var scc []*Package
for {
// Pop y from stack.
i := len(stack) - 1
y := stack[i]
stack = stack[:i]
if x != y || scc != nil {
scc = append(scc, y.mp)
}
if x == y {
break // complete
}
// x becomes y's canonical representative.
y.rep = x
}
if scc != nil {
sccs = append(sccs, scc)
}
x.scc = 1
}
}
// Visit only the updated nodes:
// the existing metadata graph has no cycles,
// so any new cycle must involve an updated node.
for id, mp := range updates {
if mp != nil {
if n := nodeOf(id); n.index == 0 { // unvisited
visit(n)
}
}
}
return sccs
}
| tools/gopls/internal/cache/metadata/graph.go/0 | {
"file_path": "tools/gopls/internal/cache/metadata/graph.go",
"repo_id": "tools",
"token_count": 4318
} | 731 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"os"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/sync/errgroup"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/internal/testenv"
)
func TestMain(m *testing.M) {
bug.PanicOnBugs = true
os.Exit(m.Run())
}
func TestMatchingPortsStdlib(t *testing.T) {
// This test checks that we don't encounter a bug when matching ports, and
// sanity checks that the optimization to use trimmed/fake file content
// before delegating to go/build.Context.MatchFile does not affect
// correctness.
if testing.Short() {
t.Skip("skipping in short mode: takes to long on slow file systems")
}
testenv.NeedsTool(t, "go")
// Load, parse and type-check the program.
cfg := &packages.Config{
Mode: packages.LoadFiles,
Tests: true,
}
pkgs, err := packages.Load(cfg, "std", "cmd")
if err != nil {
t.Fatal(err)
}
var g errgroup.Group
packages.Visit(pkgs, nil, func(pkg *packages.Package) {
for _, f := range pkg.CompiledGoFiles {
f := f
g.Go(func() error {
content, err := os.ReadFile(f)
// We report errors via t.Error, not by returning,
// so that a single test can report multiple test failures.
if err != nil {
t.Errorf("failed to read %s: %v", f, err)
return nil
}
fh := makeFakeFileHandle(protocol.URIFromPath(f), content)
fastPorts := matchingPreferredPorts(t, fh, true)
slowPorts := matchingPreferredPorts(t, fh, false)
if diff := cmp.Diff(fastPorts, slowPorts); diff != "" {
t.Errorf("%s: ports do not match (-trimmed +untrimmed):\n%s", f, diff)
return nil
}
return nil
})
}
})
g.Wait()
}
func matchingPreferredPorts(tb testing.TB, fh file.Handle, trimContent bool) map[port]unit {
content, err := fh.Content()
if err != nil {
tb.Fatal(err)
}
if trimContent {
content = trimContentForPortMatch(content)
}
path := fh.URI().Path()
matching := make(map[port]unit)
for _, port := range preferredPorts {
if port.matches(path, content) {
matching[port] = unit{}
}
}
return matching
}
func BenchmarkMatchingPreferredPorts(b *testing.B) {
// Copy of robustio_posix.go
const src = `
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build unix
// +build unix
package robustio
import (
"os"
"syscall"
"time"
)
func getFileID(filename string) (FileID, time.Time, error) {
fi, err := os.Stat(filename)
if err != nil {
return FileID{}, time.Time{}, err
}
stat := fi.Sys().(*syscall.Stat_t)
return FileID{
device: uint64(stat.Dev), // (int32 on darwin, uint64 on linux)
inode: stat.Ino,
}, fi.ModTime(), nil
}
`
fh := makeFakeFileHandle("file:///path/to/test/file.go", []byte(src))
for i := 0; i < b.N; i++ {
_ = matchingPreferredPorts(b, fh, true)
}
}
| tools/gopls/internal/cache/port_test.go/0 | {
"file_path": "tools/gopls/internal/cache/port_test.go",
"repo_id": "tools",
"token_count": 1243
} | 732 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/server"
"golang.org/x/tools/gopls/internal/settings"
"golang.org/x/tools/internal/testenv"
)
// TestCapabilities does some minimal validation of the server's adherence to the LSP.
// The checks in the test are added as changes are made and errors noticed.
func TestCapabilities(t *testing.T) {
// TODO(bcmills): This test fails on js/wasm, which is not unexpected, but the
// failure mode is that the DidOpen call below reports "no views in session",
// which seems a little too cryptic.
// Is there some missing error reporting somewhere?
testenv.NeedsTool(t, "go")
tmpDir, err := os.MkdirTemp("", "fake")
if err != nil {
t.Fatal(err)
}
tmpFile := filepath.Join(tmpDir, "fake.go")
if err := os.WriteFile(tmpFile, []byte(""), 0775); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte("module fake\n\ngo 1.12\n"), 0775); err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
app := New()
params := &protocol.ParamInitialize{}
params.RootURI = protocol.URIFromPath(tmpDir)
params.Capabilities.Workspace.Configuration = true
// Send an initialize request to the server.
ctx := context.Background()
client := newClient(app)
options := settings.DefaultOptions(app.options)
server := server.New(cache.NewSession(ctx, cache.New(nil)), client, options)
result, err := server.Initialize(ctx, params)
if err != nil {
t.Fatal(err)
}
// Validate initialization result.
if err := validateCapabilities(result); err != nil {
t.Error(err)
}
// Complete initialization of server.
if err := server.Initialized(ctx, &protocol.InitializedParams{}); err != nil {
t.Fatal(err)
}
c := newConnection(server, client)
defer c.terminate(ctx)
// Open the file on the server side.
uri := protocol.URIFromPath(tmpFile)
if err := c.Server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{
TextDocument: protocol.TextDocumentItem{
URI: uri,
LanguageID: "go",
Version: 1,
Text: `package main; func main() {};`,
},
}); err != nil {
t.Fatal(err)
}
// If we are sending a full text change, the change.Range must be nil.
// It is not enough for the Change to be empty, as that is ambiguous.
if err := c.Server.DidChange(ctx, &protocol.DidChangeTextDocumentParams{
TextDocument: protocol.VersionedTextDocumentIdentifier{
TextDocumentIdentifier: protocol.TextDocumentIdentifier{
URI: uri,
},
Version: 2,
},
ContentChanges: []protocol.TextDocumentContentChangeEvent{
{
Range: nil,
Text: `package main; func main() { fmt.Println("") }`,
},
},
}); err != nil {
t.Fatal(err)
}
// Send a code action request to validate expected types.
actions, err := c.Server.CodeAction(ctx, &protocol.CodeActionParams{
TextDocument: protocol.TextDocumentIdentifier{
URI: uri,
},
})
if err != nil {
t.Fatal(err)
}
for _, action := range actions {
// Validate that an empty command is sent along with import organization responses.
if action.Kind == protocol.SourceOrganizeImports && action.Command != nil {
t.Errorf("unexpected command for import organization")
}
}
if err := c.Server.DidSave(ctx, &protocol.DidSaveTextDocumentParams{
TextDocument: protocol.TextDocumentIdentifier{
URI: uri,
},
// LSP specifies that a file can be saved with optional text, so this field must be nil.
Text: nil,
}); err != nil {
t.Fatal(err)
}
// Send a completion request to validate expected types.
list, err := c.Server.Completion(ctx, &protocol.CompletionParams{
TextDocumentPositionParams: protocol.TextDocumentPositionParams{
TextDocument: protocol.TextDocumentIdentifier{
URI: uri,
},
Position: protocol.Position{
Line: 0,
Character: 28,
},
},
})
if err != nil {
t.Fatal(err)
}
for _, item := range list.Items {
// All other completion items should have nil commands.
// An empty command will be treated as a command with the name '' by VS Code.
// This causes VS Code to report errors to users about invalid commands.
if item.Command != nil {
t.Errorf("unexpected command for completion item")
}
// The item's TextEdit must be a pointer, as VS Code considers TextEdits
// that don't contain the cursor position to be invalid.
var textEdit = item.TextEdit.Value
switch textEdit.(type) {
case protocol.TextEdit, protocol.InsertReplaceEdit:
default:
t.Errorf("textEdit is not TextEdit nor InsertReplaceEdit, instead it is %T", textEdit)
}
}
if err := c.Server.Shutdown(ctx); err != nil {
t.Fatal(err)
}
if err := c.Server.Exit(ctx); err != nil {
t.Fatal(err)
}
}
func validateCapabilities(result *protocol.InitializeResult) error {
// If the client sends "false" for RenameProvider.PrepareSupport,
// the server must respond with a boolean.
if v, ok := result.Capabilities.RenameProvider.(bool); !ok {
return fmt.Errorf("RenameProvider must be a boolean if PrepareSupport is false (got %T)", v)
}
// The same goes for CodeActionKind.ValueSet.
if v, ok := result.Capabilities.CodeActionProvider.(bool); !ok {
return fmt.Errorf("CodeActionSupport must be a boolean if CodeActionKind.ValueSet has length 0 (got %T)", v)
}
return nil
}
| tools/gopls/internal/cmd/capabilities_test.go/0 | {
"file_path": "tools/gopls/internal/cmd/capabilities_test.go",
"repo_id": "tools",
"token_count": 1934
} | 733 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cmd
import (
"strconv"
"strings"
"unicode/utf8"
"golang.org/x/tools/gopls/internal/protocol"
)
// parseSpan returns the location represented by the input.
// Only file paths are accepted, not URIs.
// The returned span will be normalized, and thus if printed may produce a
// different string.
func parseSpan(input string) span {
uri := protocol.URIFromPath
// :0:0#0-0:0#0
valid := input
var hold, offset int
hadCol := false
suf := rstripSuffix(input)
if suf.sep == "#" {
offset = suf.num
suf = rstripSuffix(suf.remains)
}
if suf.sep == ":" {
valid = suf.remains
hold = suf.num
hadCol = true
suf = rstripSuffix(suf.remains)
}
switch {
case suf.sep == ":":
return newSpan(uri(suf.remains), newPoint(suf.num, hold, offset), point{})
case suf.sep == "-":
// we have a span, fall out of the case to continue
default:
// separator not valid, rewind to either the : or the start
return newSpan(uri(valid), newPoint(hold, 0, offset), point{})
}
// only the span form can get here
// at this point we still don't know what the numbers we have mean
// if have not yet seen a : then we might have either a line or a column depending
// on whether start has a column or not
// we build an end point and will fix it later if needed
end := newPoint(suf.num, hold, offset)
hold, offset = 0, 0
suf = rstripSuffix(suf.remains)
if suf.sep == "#" {
offset = suf.num
suf = rstripSuffix(suf.remains)
}
if suf.sep != ":" {
// turns out we don't have a span after all, rewind
return newSpan(uri(valid), end, point{})
}
valid = suf.remains
hold = suf.num
suf = rstripSuffix(suf.remains)
if suf.sep != ":" {
// line#offset only
return newSpan(uri(valid), newPoint(hold, 0, offset), end)
}
// we have a column, so if end only had one number, it is also the column
if !hadCol {
end = newPoint(suf.num, end.v.Line, end.v.Offset)
}
return newSpan(uri(suf.remains), newPoint(suf.num, hold, offset), end)
}
type suffix struct {
remains string
sep string
num int
}
func rstripSuffix(input string) suffix {
if len(input) == 0 {
return suffix{"", "", -1}
}
remains := input
// Remove optional trailing decimal number.
num := -1
last := strings.LastIndexFunc(remains, func(r rune) bool { return r < '0' || r > '9' })
if last >= 0 && last < len(remains)-1 {
number, err := strconv.ParseInt(remains[last+1:], 10, 64)
if err == nil {
num = int(number)
remains = remains[:last+1]
}
}
// now see if we have a trailing separator
r, w := utf8.DecodeLastRuneInString(remains)
// TODO(adonovan): this condition is clearly wrong. Should the third byte be '-'?
if r != ':' && r != '#' && r == '#' {
return suffix{input, "", -1}
}
remains = remains[:len(remains)-w]
return suffix{remains, string(r), num}
}
| tools/gopls/internal/cmd/parsespan.go/0 | {
"file_path": "tools/gopls/internal/cmd/parsespan.go",
"repo_id": "tools",
"token_count": 1132
} | 734 |
show diagnostic results for the specified file
Usage:
gopls [flags] check <filename>
Example: show the diagnostic results of this file:
$ gopls check internal/cmd/check.go
| tools/gopls/internal/cmd/usage/check.hlp/0 | {
"file_path": "tools/gopls/internal/cmd/usage/check.hlp",
"repo_id": "tools",
"token_count": 50
} | 735 |
display selected identifier's references
Usage:
gopls [flags] references [references-flags] <position>
Example:
$ # 1-indexed location (:line:column or :#offset) of the target identifier
$ gopls references helper/helper.go:8:6
$ gopls references helper/helper.go:#53
references-flags:
-d,-declaration
include the declaration of the specified identifier in the results
| tools/gopls/internal/cmd/usage/references.hlp/0 | {
"file_path": "tools/gopls/internal/cmd/usage/references.hlp",
"repo_id": "tools",
"token_count": 117
} | 736 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package debug exports debug information for gopls.
package debug
import (
"bytes"
"context"
"encoding/json"
"runtime"
"testing"
"golang.org/x/tools/gopls/internal/version"
)
func TestPrintVersionInfoJSON(t *testing.T) {
buf := new(bytes.Buffer)
if err := PrintVersionInfo(context.Background(), buf, true, JSON); err != nil {
t.Fatalf("PrintVersionInfo failed: %v", err)
}
res := buf.Bytes()
var got ServerVersion
if err := json.Unmarshal(res, &got); err != nil {
t.Fatalf("unexpected output: %v\n%s", err, res)
}
if g, w := got.GoVersion, runtime.Version(); g != w {
t.Errorf("go version = %v, want %v", g, w)
}
if g, w := got.Version, version.Version(); g != w {
t.Errorf("gopls version = %v, want %v", g, w)
}
// Other fields of BuildInfo may not be available during test.
}
func TestPrintVersionInfoPlainText(t *testing.T) {
buf := new(bytes.Buffer)
if err := PrintVersionInfo(context.Background(), buf, true, PlainText); err != nil {
t.Fatalf("PrintVersionInfo failed: %v", err)
}
res := buf.Bytes()
// Other fields of BuildInfo may not be available during test.
wantGoplsVersion, wantGoVersion := version.Version(), runtime.Version()
if !bytes.Contains(res, []byte(wantGoplsVersion)) || !bytes.Contains(res, []byte(wantGoVersion)) {
t.Errorf("plaintext output = %q,\nwant (version: %v, go: %v)", res, wantGoplsVersion, wantGoVersion)
}
}
| tools/gopls/internal/debug/info_test.go/0 | {
"file_path": "tools/gopls/internal/debug/info_test.go",
"repo_id": "tools",
"token_count": 549
} | 737 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fuzzy_test
import (
"bytes"
"sort"
"testing"
"golang.org/x/tools/gopls/internal/fuzzy"
)
var rolesTests = []struct {
str string
want string
}{
{str: "abc::def::goo", want: "Ccc//Ccc//Ccc"},
{str: "proto::Message", want: "Ccccc//Ccccccc"},
{str: "AbstractSWTFactory", want: "CcccccccCuuCcccccc"},
{str: "Abs012", want: "Cccccc"},
{str: "/", want: " "},
{str: "fOO", want: "CCu"},
{str: "fo_oo.o_oo", want: "Cc Cc/C Cc"},
}
func rolesString(roles []fuzzy.RuneRole) string {
var buf bytes.Buffer
for _, r := range roles {
buf.WriteByte(" /cuC"[int(r)])
}
return buf.String()
}
func TestRoles(t *testing.T) {
for _, tc := range rolesTests {
gotRoles := make([]fuzzy.RuneRole, len(tc.str))
fuzzy.RuneRoles([]byte(tc.str), gotRoles)
got := rolesString(gotRoles)
if got != tc.want {
t.Errorf("roles(%s) = %v; want %v", tc.str, got, tc.want)
}
}
}
var wordSplitTests = []struct {
input string
want []string
}{
{
input: "foo bar baz",
want: []string{"foo", "bar", "baz"},
},
{
input: "fooBarBaz",
want: []string{"foo", "Bar", "Baz"},
},
{
input: "FOOBarBAZ",
want: []string{"FOO", "Bar", "BAZ"},
},
{
input: "foo123_bar2Baz3",
want: []string{"foo123", "bar2", "Baz3"},
},
}
func TestWordSplit(t *testing.T) {
for _, tc := range wordSplitTests {
roles := fuzzy.RuneRoles([]byte(tc.input), nil)
var got []string
consumer := func(i, j int) {
got = append(got, tc.input[i:j])
}
fuzzy.Words(roles, consumer)
if eq := diffStringLists(tc.want, got); !eq {
t.Errorf("input %v: (want %v -> got %v)", tc.input, tc.want, got)
}
}
}
func diffStringLists(a, b []string) bool {
if len(a) != len(b) {
return false
}
sort.Strings(a)
sort.Strings(b)
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
var lastSegmentSplitTests = []struct {
str string
want string
}{
{
str: "identifier",
want: "identifier",
},
{
str: "two_words",
want: "two_words",
},
{
str: "first::second",
want: "second",
},
{
str: "foo.bar.FOOBar_buz123_test",
want: "FOOBar_buz123_test",
},
}
func TestLastSegment(t *testing.T) {
for _, tc := range lastSegmentSplitTests {
roles := fuzzy.RuneRoles([]byte(tc.str), nil)
got := fuzzy.LastSegment(tc.str, roles)
if got != tc.want {
t.Errorf("str %v: want %v; got %v", tc.str, tc.want, got)
}
}
}
func BenchmarkRoles(b *testing.B) {
str := "AbstractSWTFactory"
out := make([]fuzzy.RuneRole, len(str))
for i := 0; i < b.N; i++ {
fuzzy.RuneRoles([]byte(str), out)
}
b.SetBytes(int64(len(str)))
}
| tools/gopls/internal/fuzzy/input_test.go/0 | {
"file_path": "tools/gopls/internal/fuzzy/input_test.go",
"repo_id": "tools",
"token_count": 1257
} | 738 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package completion
import (
"context"
"go/types"
"strings"
"time"
)
// MaxDeepCompletions limits deep completion results because in most cases
// there are too many to be useful.
const MaxDeepCompletions = 3
// deepCompletionState stores our state as we search for deep completions.
// "deep completion" refers to searching into objects' fields and methods to
// find more completion candidates.
type deepCompletionState struct {
// enabled indicates whether deep completion is permitted.
enabled bool
// queueClosed is used to disable adding new sub-fields to search queue
// once we're running out of our time budget.
queueClosed bool
// thisQueue holds the current breadth first search queue.
thisQueue []candidate
// nextQueue holds the next breadth first search iteration's queue.
nextQueue []candidate
// highScores tracks the highest deep candidate scores we have found
// so far. This is used to avoid work for low scoring deep candidates.
highScores [MaxDeepCompletions]float64
// candidateCount is the count of unique deep candidates encountered
// so far.
candidateCount int
}
// enqueue adds a candidate to the search queue.
func (s *deepCompletionState) enqueue(cand candidate) {
s.nextQueue = append(s.nextQueue, cand)
}
// scorePenalty computes a deep candidate score penalty. A candidate is
// penalized based on depth to favor shallower candidates. We also give a
// slight bonus to unexported objects and a slight additional penalty to
// function objects.
func (s *deepCompletionState) scorePenalty(cand *candidate) float64 {
var deepPenalty float64
for _, dc := range cand.path {
deepPenalty++
if !dc.Exported() {
deepPenalty -= 0.1
}
if _, isSig := dc.Type().Underlying().(*types.Signature); isSig {
deepPenalty += 0.1
}
}
// Normalize penalty to a max depth of 10.
return deepPenalty / 10
}
// isHighScore returns whether score is among the top MaxDeepCompletions deep
// candidate scores encountered so far. If so, it adds score to highScores,
// possibly displacing an existing high score.
func (s *deepCompletionState) isHighScore(score float64) bool {
// Invariant: s.highScores is sorted with highest score first. Unclaimed
// positions are trailing zeros.
// If we beat an existing score then take its spot.
for i, deepScore := range s.highScores {
if score <= deepScore {
continue
}
if deepScore != 0 && i != len(s.highScores)-1 {
// If this wasn't an empty slot then we need to scooch everyone
// down one spot.
copy(s.highScores[i+1:], s.highScores[i:])
}
s.highScores[i] = score
return true
}
return false
}
// newPath returns path from search root for an object following a given
// candidate.
func (s *deepCompletionState) newPath(cand candidate, obj types.Object) []types.Object {
path := make([]types.Object, len(cand.path)+1)
copy(path, cand.path)
path[len(path)-1] = obj
return path
}
// deepSearch searches a candidate and its subordinate objects for completion
// items if deep completion is enabled and adds the valid candidates to
// completion items.
func (c *completer) deepSearch(ctx context.Context, minDepth int, deadline *time.Time) {
defer func() {
// We can return early before completing the search, so be sure to
// clear out our queues to not impact any further invocations.
c.deepState.thisQueue = c.deepState.thisQueue[:0]
c.deepState.nextQueue = c.deepState.nextQueue[:0]
}()
depth := 0 // current depth being processed
// Stop reports whether we should stop the search immediately.
stop := func() bool {
// Context cancellation indicates that the actual completion operation was
// cancelled, so ignore minDepth and deadline.
select {
case <-ctx.Done():
return true
default:
}
// Otherwise, only stop if we've searched at least minDepth and reached the deadline.
return depth > minDepth && deadline != nil && time.Now().After(*deadline)
}
for len(c.deepState.nextQueue) > 0 {
depth++
if stop() {
return
}
c.deepState.thisQueue, c.deepState.nextQueue = c.deepState.nextQueue, c.deepState.thisQueue[:0]
outer:
for _, cand := range c.deepState.thisQueue {
obj := cand.obj
if obj == nil {
continue
}
// At the top level, dedupe by object.
if len(cand.path) == 0 {
if c.seen[obj] {
continue
}
c.seen[obj] = true
}
// If obj is not accessible because it lives in another package and is
// not exported, don't treat it as a completion candidate unless it's
// a package completion candidate.
if !c.completionContext.packageCompletion &&
obj.Pkg() != nil && obj.Pkg() != c.pkg.Types() && !obj.Exported() {
continue
}
// If we want a type name, don't offer non-type name candidates.
// However, do offer package names since they can contain type names,
// and do offer any candidate without a type since we aren't sure if it
// is a type name or not (i.e. unimported candidate).
if c.wantTypeName() && obj.Type() != nil && !isTypeName(obj) && !isPkgName(obj) {
continue
}
// When searching deep, make sure we don't have a cycle in our chain.
// We don't dedupe by object because we want to allow both "foo.Baz"
// and "bar.Baz" even though "Baz" is represented the same types.Object
// in both.
for _, seenObj := range cand.path {
if seenObj == obj {
continue outer
}
}
c.addCandidate(ctx, &cand)
c.deepState.candidateCount++
if c.opts.budget > 0 && c.deepState.candidateCount%100 == 0 {
if stop() {
return
}
spent := float64(time.Since(c.startTime)) / float64(c.opts.budget)
// If we are almost out of budgeted time, no further elements
// should be added to the queue. This ensures remaining time is
// used for processing current queue.
if !c.deepState.queueClosed && spent >= 0.85 {
c.deepState.queueClosed = true
}
}
// if deep search is disabled, don't add any more candidates.
if !c.deepState.enabled || c.deepState.queueClosed {
continue
}
// Searching members for a type name doesn't make sense.
if isTypeName(obj) {
continue
}
if obj.Type() == nil {
continue
}
// Don't search embedded fields because they were already included in their
// parent's fields.
if v, ok := obj.(*types.Var); ok && v.Embedded() {
continue
}
if sig, ok := obj.Type().Underlying().(*types.Signature); ok {
// If obj is a function that takes no arguments and returns one
// value, keep searching across the function call.
if sig.Params().Len() == 0 && sig.Results().Len() == 1 {
path := c.deepState.newPath(cand, obj)
// The result of a function call is not addressable.
c.methodsAndFields(sig.Results().At(0).Type(), false, cand.imp, func(newCand candidate) {
newCand.pathInvokeMask = cand.pathInvokeMask | (1 << uint64(len(cand.path)))
newCand.path = path
c.deepState.enqueue(newCand)
})
}
}
path := c.deepState.newPath(cand, obj)
switch obj := obj.(type) {
case *types.PkgName:
c.packageMembers(obj.Imported(), stdScore, cand.imp, func(newCand candidate) {
newCand.pathInvokeMask = cand.pathInvokeMask
newCand.path = path
c.deepState.enqueue(newCand)
})
default:
c.methodsAndFields(obj.Type(), cand.addressable, cand.imp, func(newCand candidate) {
newCand.pathInvokeMask = cand.pathInvokeMask
newCand.path = path
c.deepState.enqueue(newCand)
})
}
}
}
}
// addCandidate adds a completion candidate to suggestions, without searching
// its members for more candidates.
func (c *completer) addCandidate(ctx context.Context, cand *candidate) {
obj := cand.obj
if c.matchingCandidate(cand) {
cand.score *= highScore
if p := c.penalty(cand); p > 0 {
cand.score *= (1 - p)
}
} else if isTypeName(obj) {
// If obj is a *types.TypeName that didn't otherwise match, check
// if a literal object of this type makes a good candidate.
// We only care about named types (i.e. don't want builtin types).
if _, isNamed := obj.Type().(*types.Named); isNamed {
c.literal(ctx, obj.Type(), cand.imp)
}
}
// Lower score of method calls so we prefer fields and vars over calls.
if cand.hasMod(invoke) {
if sig, ok := obj.Type().Underlying().(*types.Signature); ok && sig.Recv() != nil {
cand.score *= 0.9
}
}
// Prefer private objects over public ones.
if !obj.Exported() && obj.Parent() != types.Universe {
cand.score *= 1.1
}
// Slight penalty for index modifier (e.g. changing "foo" to
// "foo[]") to curb false positives.
if cand.hasMod(index) {
cand.score *= 0.9
}
// Favor shallow matches by lowering score according to depth.
cand.score -= cand.score * c.deepState.scorePenalty(cand)
if cand.score < 0 {
cand.score = 0
}
cand.name = deepCandName(cand)
if item, err := c.item(ctx, *cand); err == nil {
c.items = append(c.items, item)
}
}
// deepCandName produces the full candidate name including any
// ancestor objects. For example, "foo.bar().baz" for candidate "baz".
func deepCandName(cand *candidate) string {
totalLen := len(cand.obj.Name())
for i, obj := range cand.path {
totalLen += len(obj.Name()) + 1
if cand.pathInvokeMask&(1<<uint16(i)) > 0 {
totalLen += 2
}
}
var buf strings.Builder
buf.Grow(totalLen)
for i, obj := range cand.path {
buf.WriteString(obj.Name())
if cand.pathInvokeMask&(1<<uint16(i)) > 0 {
buf.WriteByte('(')
buf.WriteByte(')')
}
buf.WriteByte('.')
}
buf.WriteString(cand.obj.Name())
return buf.String()
}
// penalty reports a score penalty for cand in the range (0, 1).
// For example, a candidate is penalized if it has already been used
// in another switch case statement.
func (c *completer) penalty(cand *candidate) float64 {
for _, p := range c.inference.penalized {
if c.objChainMatches(cand, p.objChain) {
return p.penalty
}
}
return 0
}
// objChainMatches reports whether cand combined with the surrounding
// object prefix matches chain.
func (c *completer) objChainMatches(cand *candidate, chain []types.Object) bool {
// For example, when completing:
//
// foo.ba<>
//
// If we are considering the deep candidate "bar.baz", cand is baz,
// objChain is [foo] and deepChain is [bar]. We would match the
// chain [foo, bar, baz].
if len(chain) != len(c.inference.objChain)+len(cand.path)+1 {
return false
}
if chain[len(chain)-1] != cand.obj {
return false
}
for i, o := range c.inference.objChain {
if chain[i] != o {
return false
}
}
for i, o := range cand.path {
if chain[i+len(c.inference.objChain)] != o {
return false
}
}
return true
}
| tools/gopls/internal/golang/completion/deep_completion.go/0 | {
"file_path": "tools/gopls/internal/golang/completion/deep_completion.go",
"repo_id": "tools",
"token_count": 3765
} | 739 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package completion
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"strings"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/golang"
"golang.org/x/tools/gopls/internal/golang/completion/snippet"
"golang.org/x/tools/gopls/internal/protocol"
)
// addStatementCandidates adds full statement completion candidates
// appropriate for the current context.
func (c *completer) addStatementCandidates() {
c.addErrCheck()
c.addAssignAppend()
c.addReturnZeroValues()
}
// addAssignAppend offers a completion candidate of the form:
//
// someSlice = append(someSlice, )
//
// 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, )".
//
// 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
}
ident, _ := c.path[0].(*ast.Ident)
if ident == nil {
return
}
var (
// sliceText is the full name of our slice object, e.g. "s.abc" in
// "s.abc = app<>".
sliceText string
// needsLHS is true if we need to prepend the LHS slice name and
// "=" to our candidate.
needsLHS = false
fset = c.pkg.FileSet()
)
switch n := c.path[1].(type) {
case *ast.AssignStmt:
// We are already in an assignment. Make sure our prefix matches "append".
if c.matcher.Score("append") <= 0 {
return
}
exprIdx := exprAtPos(c.pos, n.Rhs)
if exprIdx == len(n.Rhs) || exprIdx > len(n.Lhs)-1 {
return
}
lhsType := c.pkg.TypesInfo().TypeOf(n.Lhs[exprIdx])
if lhsType == nil {
return
}
// Make sure our corresponding LHS object is a slice.
if _, isSlice := lhsType.Underlying().(*types.Slice); !isSlice {
return
}
// The name or our slice is whatever's in the LHS expression.
sliceText = golang.FormatNode(fset, n.Lhs[exprIdx])
case *ast.SelectorExpr:
// Make sure we are a selector at the beginning of a statement.
if _, parentIsExprtStmt := c.path[2].(*ast.ExprStmt); !parentIsExprtStmt {
return
}
// So far we only know the first part of our slice name. For
// example in "s.a<>" we only know our slice begins with "s."
// since the user could still be typing.
sliceText = golang.FormatNode(fset, n.X) + "."
needsLHS = true
case *ast.ExprStmt:
needsLHS = true
default:
return
}
var (
label string
snip snippet.Builder
score = highScore
)
if needsLHS {
// Offer the long form assign + append candidate if our best
// candidate is a slice.
bestItem := c.topCandidate()
if bestItem == nil || !bestItem.isSlice {
return
}
// Don't rank the full form assign + append candidate above the
// slice itself.
score = bestItem.Score - 0.01
// Fill in rest of sliceText now that we have the object name.
sliceText += bestItem.Label
// Fill in the candidate's LHS bits.
label = fmt.Sprintf("%s = ", bestItem.Label)
snip.WriteText(label)
}
snip.WriteText(fmt.Sprintf("append(%s, ", sliceText))
snip.WritePlaceholder(nil)
snip.WriteText(")")
c.items = append(c.items, CompletionItem{
Label: label + fmt.Sprintf("append(%s, )", sliceText),
Kind: protocol.FunctionCompletion,
Score: score,
snippet: &snip,
})
}
// topCandidate returns the strictly highest scoring candidate
// collected so far. If the top two candidates have the same score,
// nil is returned.
func (c *completer) topCandidate() *CompletionItem {
var bestItem, secondBestItem *CompletionItem
for i := range c.items {
if bestItem == nil || c.items[i].Score > bestItem.Score {
bestItem = &c.items[i]
} else if secondBestItem == nil || c.items[i].Score > secondBestItem.Score {
secondBestItem = &c.items[i]
}
}
// If secondBestItem has the same score, bestItem isn't
// the strict best.
if secondBestItem != nil && secondBestItem.Score == bestItem.Score {
return nil
}
return bestItem
}
// addErrCheck offers a completion candidate of the form:
//
// 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)
// }
//
// The position must be in a function that returns an error, and the
// statement preceding the position must be an assignment where the
// final LHS object is an error. addErrCheck will synthesize
// zero values as necessary to make the return statement valid.
func (c *completer) addErrCheck() {
if len(c.path) < 2 || c.enclosingFunc == nil || !c.opts.placeholders {
return
}
var (
errorType = types.Universe.Lookup("error").Type()
result = c.enclosingFunc.sig.Results()
testVar = getTestVar(c.enclosingFunc, c.pkg)
isTest = testVar != ""
doesNotReturnErr = result.Len() == 0 || !types.Identical(result.At(result.Len()-1).Type(), errorType)
)
// Make sure our enclosing function is a Test func or returns an error.
if !isTest && doesNotReturnErr {
return
}
prevLine := prevStmt(c.pos, c.path)
if prevLine == nil {
return
}
// Make sure our preceding statement was as assignment.
assign, _ := prevLine.(*ast.AssignStmt)
if assign == nil || len(assign.Lhs) == 0 {
return
}
lastAssignee := assign.Lhs[len(assign.Lhs)-1]
// Make sure the final assignee is an error.
if !types.Identical(c.pkg.TypesInfo().TypeOf(lastAssignee), errorType) {
return
}
var (
// errVar is e.g. "err" in "foo, err := bar()".
errVar = golang.FormatNode(c.pkg.FileSet(), lastAssignee)
// Whether we need to include the "if" keyword in our candidate.
needsIf = true
)
// If the returned error from the previous statement is "_", it is not a real object.
// If we don't have an error, and the function signature takes a testing.TB that is either ignored
// or an "_", then we also can't call t.Fatal(err).
if errVar == "_" {
return
}
// Below we try to detect if the user has already started typing "if
// err" so we can replace what they've typed with our complete
// statement.
switch n := c.path[0].(type) {
case *ast.Ident:
switch c.path[1].(type) {
case *ast.ExprStmt:
// This handles:
//
// f, err := os.Open("foo")
// i<>
// Make sure they are typing "if".
if c.matcher.Score("if") <= 0 {
return
}
case *ast.IfStmt:
// This handles:
//
// f, err := os.Open("foo")
// if er<>
// Make sure they are typing the error's name.
if c.matcher.Score(errVar) <= 0 {
return
}
needsIf = false
default:
return
}
case *ast.IfStmt:
// This handles:
//
// f, err := os.Open("foo")
// if <>
// Avoid false positives by ensuring the if's cond is a bad
// expression. For example, don't offer the completion in cases
// like "if <> somethingElse".
if _, bad := n.Cond.(*ast.BadExpr); !bad {
return
}
// If "if" is our direct prefix, we need to include it in our
// candidate since the existing "if" will be overwritten.
needsIf = c.pos == n.Pos()+token.Pos(len("if"))
}
// Build up a snippet that looks like:
//
// if err != nil {
// return <zero value>, ..., ${1:err}
// }
//
// We make the error a placeholder so it is easy to alter the error.
var snip snippet.Builder
if needsIf {
snip.WriteText("if ")
}
snip.WriteText(fmt.Sprintf("%s != nil {\n\t", errVar))
var label string
if isTest {
snip.WriteText(fmt.Sprintf("%s.Fatal(%s)", testVar, errVar))
label = fmt.Sprintf("%[1]s != nil { %[2]s.Fatal(%[1]s) }", errVar, testVar)
} else {
snip.WriteText("return ")
for i := 0; i < result.Len()-1; i++ {
snip.WriteText(formatZeroValue(result.At(i).Type(), c.qf))
snip.WriteText(", ")
}
snip.WritePlaceholder(func(b *snippet.Builder) {
b.WriteText(errVar)
})
label = fmt.Sprintf("%[1]s != nil { return %[1]s }", errVar)
}
snip.WriteText("\n}")
if needsIf {
label = "if " + label
}
c.items = append(c.items, CompletionItem{
Label: label,
Kind: protocol.SnippetCompletion,
Score: highScore,
snippet: &snip,
})
}
// getTestVar checks the function signature's input parameters and returns
// the name of the first parameter that implements "testing.TB". For example,
// func someFunc(t *testing.T) returns the string "t", func someFunc(b *testing.B)
// returns "b" etc. An empty string indicates that the function signature
// does not take a testing.TB parameter or does so but is ignored such
// as func someFunc(*testing.T).
func getTestVar(enclosingFunc *funcInfo, pkg *cache.Package) string {
if enclosingFunc == nil || enclosingFunc.sig == nil {
return ""
}
var testingPkg *types.Package
for _, p := range pkg.Types().Imports() {
if p.Path() == "testing" {
testingPkg = p
break
}
}
if testingPkg == nil {
return ""
}
tbObj := testingPkg.Scope().Lookup("TB")
if tbObj == nil {
return ""
}
iface, ok := tbObj.Type().Underlying().(*types.Interface)
if !ok {
return ""
}
sig := enclosingFunc.sig
for i := 0; i < sig.Params().Len(); i++ {
param := sig.Params().At(i)
if param.Name() == "_" {
continue
}
if !types.Implements(param.Type(), iface) {
continue
}
return param.Name()
}
return ""
}
// addReturnZeroValues offers a snippet candidate on the form:
//
// return 0, "", nil
//
// Requires a partially or fully written return keyword at position.
// Requires current position to be in a function with more than
// zero return parameters.
func (c *completer) addReturnZeroValues() {
if len(c.path) < 2 || c.enclosingFunc == nil || !c.opts.placeholders {
return
}
result := c.enclosingFunc.sig.Results()
if result.Len() == 0 {
return
}
// Offer just less than we expect from return as a keyword.
var score = stdScore - 0.01
switch c.path[0].(type) {
case *ast.ReturnStmt, *ast.Ident:
f := c.matcher.Score("return")
if f <= 0 {
return
}
score *= float64(f)
default:
return
}
// The snippet will have a placeholder over each return value.
// The label will not.
var snip snippet.Builder
var label strings.Builder
snip.WriteText("return ")
fmt.Fprintf(&label, "return ")
for i := 0; i < result.Len(); i++ {
if i > 0 {
snip.WriteText(", ")
fmt.Fprintf(&label, ", ")
}
zero := formatZeroValue(result.At(i).Type(), c.qf)
snip.WritePlaceholder(func(b *snippet.Builder) {
b.WriteText(zero)
})
fmt.Fprintf(&label, zero)
}
c.items = append(c.items, CompletionItem{
Label: label.String(),
Kind: protocol.SnippetCompletion,
Score: score,
snippet: &snip,
})
}
| tools/gopls/internal/golang/completion/statements.go/0 | {
"file_path": "tools/gopls/internal/golang/completion/statements.go",
"repo_id": "tools",
"token_count": 4176
} | 740 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"bytes"
"context"
"encoding/json"
"fmt"
"go/ast"
"go/constant"
"go/doc"
"go/format"
"go/token"
"go/types"
"io/fs"
"path/filepath"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"unicode/utf8"
"golang.org/x/text/unicode/runenames"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/types/typeutil"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/cache/metadata"
"golang.org/x/tools/gopls/internal/cache/parsego"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/settings"
gastutil "golang.org/x/tools/gopls/internal/util/astutil"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/gopls/internal/util/safetoken"
"golang.org/x/tools/gopls/internal/util/slices"
"golang.org/x/tools/gopls/internal/util/typesutil"
"golang.org/x/tools/internal/aliases"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/stdlib"
"golang.org/x/tools/internal/tokeninternal"
"golang.org/x/tools/internal/typeparams"
"golang.org/x/tools/internal/typesinternal"
)
// hoverJSON contains the structured result of a hover query. It is
// formatted in one of several formats as determined by the HoverKind
// setting, one of which is JSON.
//
// We believe this is used only by govim.
// TODO(adonovan): see if we can wean all clients of this interface.
type hoverJSON struct {
// Synopsis is a single sentence synopsis of the symbol's documentation.
Synopsis string `json:"synopsis"`
// FullDocumentation is the symbol's full documentation.
FullDocumentation string `json:"fullDocumentation"`
// Signature is the symbol's signature.
Signature string `json:"signature"`
// SingleLine is a single line describing the symbol.
// This is recommended only for use in clients that show a single line for hover.
SingleLine string `json:"singleLine"`
// SymbolName is the human-readable name to use for the symbol in links.
SymbolName string `json:"symbolName"`
// LinkPath is the pkg.go.dev link for the given symbol.
// For example, the "go/ast" part of "pkg.go.dev/go/ast#Node".
// It may have a module version suffix "@v1.2.3".
LinkPath string `json:"linkPath"`
// LinkAnchor is the pkg.go.dev link anchor for the given symbol.
// For example, the "Node" part of "pkg.go.dev/go/ast#Node".
LinkAnchor string `json:"linkAnchor"`
// stdVersion is the Go release version at which this symbol became available.
// It is nil for non-std library.
stdVersion *stdlib.Version
// New fields go below, and are unexported. The existing
// exported fields are underspecified and have already
// constrained our movements too much. A detailed JSON
// interface might be nice, but it needs a design and a
// precise specification.
// typeDecl is the declaration syntax for a type,
// or "" for a non-type.
typeDecl string
// methods is the list of descriptions of methods of a type,
// omitting any that are obvious from typeDecl.
// It is "" for a non-type.
methods string
// promotedFields is the list of descriptions of accessible
// fields of a (struct) type that were promoted through an
// embedded field.
promotedFields string
}
// 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 Hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position, pkgURL func(path PackagePath, fragment string) protocol.URI) (*protocol.Hover, error) {
ctx, done := event.Start(ctx, "golang.Hover")
defer done()
rng, h, err := hover(ctx, snapshot, fh, position)
if err != nil {
return nil, err
}
if h == nil {
return nil, nil
}
hover, err := formatHover(h, snapshot.Options(), pkgURL)
if err != nil {
return nil, err
}
return &protocol.Hover{
Contents: protocol.MarkupContent{
Kind: snapshot.Options().PreferredContentFormat,
Value: hover,
},
Range: rng,
}, nil
}
// hover computes hover information at the given position. If we do not support
// hovering at the position, it returns _, nil, nil: an error is only returned
// if the position is valid but we fail to compute hover information.
//
// TODO(adonovan): strength-reduce file.Handle to protocol.DocumentURI.
func hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pp protocol.Position) (protocol.Range, *hoverJSON, error) {
// Check for hover inside the builtin file before attempting type checking
// below. NarrowestPackageForFile may or may not succeed, depending on
// whether this is a GOROOT view, but even if it does succeed the resulting
// package will be command-line-arguments package. The user should get a
// hover for the builtin object, not the object type checked from the
// builtin.go.
if snapshot.IsBuiltin(fh.URI()) {
pgf, err := snapshot.BuiltinFile(ctx)
if err != nil {
return protocol.Range{}, nil, err
}
pos, err := pgf.PositionPos(pp)
if err != nil {
return protocol.Range{}, nil, err
}
path, _ := astutil.PathEnclosingInterval(pgf.File, pos, pos)
if id, ok := path[0].(*ast.Ident); ok {
rng, err := pgf.NodeRange(id)
if err != nil {
return protocol.Range{}, nil, err
}
var obj types.Object
if id.Name == "Error" {
obj = types.Universe.Lookup("error").Type().Underlying().(*types.Interface).Method(0)
} else {
obj = types.Universe.Lookup(id.Name)
}
if obj != nil {
h, err := hoverBuiltin(ctx, snapshot, obj)
return rng, h, err
}
}
return protocol.Range{}, nil, nil // no object to hover
}
pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
if err != nil {
return protocol.Range{}, nil, err
}
pos, err := pgf.PositionPos(pp)
if err != nil {
return protocol.Range{}, nil, err
}
// Handle hovering over the package name, which does not have an associated
// object.
// As with import paths, we allow hovering just after the package name.
if pgf.File.Name != nil && gastutil.NodeContains(pgf.File.Name, pos) {
return hoverPackageName(pkg, pgf)
}
// Handle hovering over embed directive argument.
pattern, embedRng := parseEmbedDirective(pgf.Mapper, pp)
if pattern != "" {
return hoverEmbed(fh, embedRng, pattern)
}
// hoverRange is the range reported to the client (e.g. for highlighting).
// It may be an expansion around the selected identifier,
// for instance when hovering over a linkname directive or doc link.
var hoverRange *protocol.Range
// Handle linkname directive by overriding what to look for.
if pkgPath, name, offset := parseLinkname(pgf.Mapper, pp); pkgPath != "" && name != "" {
// rng covering 2nd linkname argument: pkgPath.name.
rng, err := pgf.PosRange(pgf.Tok.Pos(offset), pgf.Tok.Pos(offset+len(pkgPath)+len(".")+len(name)))
if err != nil {
return protocol.Range{}, nil, fmt.Errorf("range over linkname arg: %w", err)
}
hoverRange = &rng
pkg, pgf, pos, err = findLinkname(ctx, snapshot, PackagePath(pkgPath), name)
if err != nil {
return protocol.Range{}, nil, fmt.Errorf("find linkname: %w", err)
}
}
// Handle hovering over a doc link
if obj, rng, _ := parseDocLink(pkg, pgf, pos); obj != nil {
// Built-ins have no position.
if isBuiltin(obj) {
h, err := hoverBuiltin(ctx, snapshot, obj)
return rng, h, err
}
// Find position in declaring file.
hoverRange = &rng
objURI := safetoken.StartPosition(pkg.FileSet(), obj.Pos())
pkg, pgf, err = NarrowestPackageForFile(ctx, snapshot, protocol.URIFromPath(objURI.Filename))
if err != nil {
return protocol.Range{}, nil, err
}
pos = pgf.Tok.Pos(objURI.Offset)
}
// Handle hovering over import paths, which do not have an associated
// identifier.
for _, spec := range pgf.File.Imports {
if gastutil.NodeContains(spec, pos) {
rng, hoverJSON, err := hoverImport(ctx, snapshot, pkg, pgf, spec)
if err != nil {
return protocol.Range{}, nil, err
}
if hoverRange == nil {
hoverRange = &rng
}
return *hoverRange, hoverJSON, nil // (hoverJSON may be nil)
}
}
// Handle hovering over (non-import-path) literals.
if path, _ := astutil.PathEnclosingInterval(pgf.File, pos, pos); len(path) > 0 {
if lit, _ := path[0].(*ast.BasicLit); lit != nil {
return hoverLit(pgf, lit, pos)
}
}
// Handle hover over identifier.
// The general case: compute hover information for the object referenced by
// the identifier at pos.
ident, obj, selectedType := referencedObject(pkg, pgf, pos)
if obj == nil || ident == nil {
return protocol.Range{}, nil, nil // no object to hover
}
// Unless otherwise specified, rng covers the ident being hovered.
if hoverRange == nil {
rng, err := pgf.NodeRange(ident)
if err != nil {
return protocol.Range{}, nil, err
}
hoverRange = &rng
}
// By convention, we qualify hover information relative to the package
// from which the request originated.
qf := typesutil.FileQualifier(pgf.File, pkg.Types(), pkg.TypesInfo())
// Handle type switch identifiers as a special case, since they don't have an
// object.
//
// There's not much useful information to provide.
if selectedType != nil {
fakeObj := types.NewVar(obj.Pos(), obj.Pkg(), obj.Name(), selectedType)
signature := types.ObjectString(fakeObj, qf)
return *hoverRange, &hoverJSON{
Signature: signature,
SingleLine: signature,
SymbolName: fakeObj.Name(),
}, nil
}
if isBuiltin(obj) {
// Built-ins have no position.
h, err := hoverBuiltin(ctx, snapshot, obj)
return *hoverRange, h, err
}
// For all other objects, consider the full syntax of their declaration in
// order to correctly compute their documentation, signature, and link.
//
// Beware: decl{PGF,Pos} are not necessarily associated with pkg.FileSet().
declPGF, declPos, err := parseFull(ctx, snapshot, pkg.FileSet(), obj.Pos())
if err != nil {
return protocol.Range{}, nil, fmt.Errorf("re-parsing declaration of %s: %v", obj.Name(), err)
}
decl, spec, field := findDeclInfo([]*ast.File{declPGF.File}, declPos) // may be nil^3
comment := chooseDocComment(decl, spec, field)
docText := comment.Text()
// By default, types.ObjectString provides a reasonable signature.
signature := objectString(obj, qf, declPos, declPGF.Tok, spec)
singleLineSignature := signature
// Display struct tag for struct fields at the end of the signature.
if field != nil && field.Tag != nil {
signature += " " + field.Tag.Value
}
// TODO(rfindley): we could do much better for inferred signatures.
// TODO(adonovan): fuse the two calls below.
if inferred := inferredSignature(pkg.TypesInfo(), ident); inferred != nil {
if s := inferredSignatureString(obj, qf, inferred); s != "" {
signature = s
}
}
// Compute size information for types,
// and (size, offset) for struct fields.
//
// Also, if a struct type's field ordering is significantly
// wasteful of space, report its optimal size.
//
// This information is useful when debugging crashes or
// optimizing layout. To reduce distraction, we show it only
// when hovering over the declaring identifier,
// but not referring identifiers.
//
// Size and alignment vary across OS/ARCH.
// Gopls will select the appropriate build configuration when
// viewing a type declaration in a build-tagged file, but will
// use the default build config for all other types, even
// if they embed platform-variant types.
//
var sizeOffset string // optional size/offset description
if def, ok := pkg.TypesInfo().Defs[ident]; ok && ident.Pos() == def.Pos() {
// This is the declaring identifier.
// (We can't simply use ident.Pos() == obj.Pos() because
// referencedObject prefers the TypeName for an embedded field).
// format returns the decimal and hex representation of x.
format := func(x int64) string {
if x < 10 {
return fmt.Sprintf("%d", x)
}
return fmt.Sprintf("%[1]d (%#[1]x)", x)
}
path := pathEnclosingObjNode(pgf.File, pos)
// Build string of form "size=... (X% wasted), offset=...".
size, wasted, offset := computeSizeOffsetInfo(pkg, path, obj)
var buf strings.Builder
if size >= 0 {
fmt.Fprintf(&buf, "size=%s", format(size))
if wasted >= 20 { // >=20% wasted
fmt.Fprintf(&buf, " (%d%% wasted)", wasted)
}
}
if offset >= 0 {
if buf.Len() > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "offset=%s", format(offset))
}
sizeOffset = buf.String()
}
var typeDecl, methods, fields string
// For "objects defined by a type spec", the signature produced by
// objectString is insufficient:
// (1) large structs are formatted poorly, with no newlines
// (2) we lose inline comments
// Furthermore, we include a summary of their method set.
_, isTypeName := obj.(*types.TypeName)
_, isTypeParam := aliases.Unalias(obj.Type()).(*types.TypeParam)
if isTypeName && !isTypeParam {
spec, ok := spec.(*ast.TypeSpec)
if !ok {
// We cannot find a TypeSpec for this type or alias declaration
// (that is not a type parameter or a built-in).
// This should be impossible even for ill-formed trees;
// we suspect that AST repair may be creating inconsistent
// positions. Don't report a bug in that case. (#64241)
errorf := fmt.Errorf
if !declPGF.Fixed() {
errorf = bug.Errorf
}
return protocol.Range{}, nil, errorf("type name %q without type spec", obj.Name())
}
// Format the type's declaration syntax.
{
// Don't duplicate comments.
spec2 := *spec
spec2.Doc = nil
spec2.Comment = nil
var b strings.Builder
b.WriteString("type ")
fset := tokeninternal.FileSetFor(declPGF.Tok)
// TODO(adonovan): use a smarter formatter that omits
// inaccessible fields (non-exported ones from other packages).
if err := format.Node(&b, fset, &spec2); err != nil {
return protocol.Range{}, nil, err
}
typeDecl = b.String()
// Splice in size/offset at end of first line.
// "type T struct { // size=..."
if sizeOffset != "" {
nl := strings.IndexByte(typeDecl, '\n')
if nl < 0 {
nl = len(typeDecl)
}
typeDecl = typeDecl[:nl] + " // " + sizeOffset + typeDecl[nl:]
}
}
// Promoted fields
//
// Show a table of accessible fields of the (struct)
// type that may not be visible in the syntax (above)
// due to promotion through embedded fields.
//
// Example:
//
// // Embedded fields:
// foo int // through x.y
// z string // through x.y
if prom := promotedFields(obj.Type(), pkg.Types()); len(prom) > 0 {
var b strings.Builder
b.WriteString("// Embedded fields:\n")
w := tabwriter.NewWriter(&b, 0, 8, 1, ' ', 0)
for _, f := range prom {
fmt.Fprintf(w, "%s\t%s\t// through %s\t\n",
f.field.Name(),
types.TypeString(f.field.Type(), qf),
f.path)
}
w.Flush()
b.WriteByte('\n')
fields = b.String()
}
// -- methods --
// For an interface type, explicit methods will have
// already been displayed when the node was formatted
// above. Don't list these again.
var skip map[string]bool
if iface, ok := spec.Type.(*ast.InterfaceType); ok {
if iface.Methods.List != nil {
for _, m := range iface.Methods.List {
if len(m.Names) == 1 {
if skip == nil {
skip = make(map[string]bool)
}
skip[m.Names[0].Name] = true
}
}
}
}
// Display all the type's accessible methods,
// including those that require a pointer receiver,
// and those promoted from embedded struct fields or
// embedded interfaces.
var b strings.Builder
for _, m := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
if !accessibleTo(m.Obj(), pkg.Types()) {
continue // inaccessible
}
if skip[m.Obj().Name()] {
continue // redundant with format.Node above
}
if b.Len() > 0 {
b.WriteByte('\n')
}
// Use objectString for its prettier rendering of method receivers.
b.WriteString(objectString(m.Obj(), qf, token.NoPos, nil, nil))
}
methods = b.String()
signature = typeDecl + "\n" + methods
} else {
// Non-types
if sizeOffset != "" {
signature += " // " + sizeOffset
}
}
// Compute link data (on pkg.go.dev or other documentation host).
//
// If linkPath is empty, the symbol is not linkable.
var (
linkName string // => link title, always non-empty
linkPath string // => link path
anchor string // link anchor
linkMeta *metadata.Package // metadata for the linked package
)
{
linkMeta = findFileInDeps(snapshot, pkg.Metadata(), declPGF.URI)
if linkMeta == nil {
return protocol.Range{}, nil, bug.Errorf("no package data for %s", declPGF.URI)
}
// For package names, we simply link to their imported package.
if pkgName, ok := obj.(*types.PkgName); ok {
linkName = pkgName.Name()
linkPath = pkgName.Imported().Path()
impID := linkMeta.DepsByPkgPath[PackagePath(pkgName.Imported().Path())]
linkMeta = snapshot.Metadata(impID)
if linkMeta == nil {
// Broken imports have fake package paths, so it is not a bug if we
// don't have metadata. As of writing, there is no way to distinguish
// broken imports from a true bug where expected metadata is missing.
return protocol.Range{}, nil, fmt.Errorf("no package data for %s", declPGF.URI)
}
} else {
// For all others, check whether the object is in the package scope, or
// an exported field or method of an object in the package scope.
//
// We try to match pkgsite's heuristics for what is linkable, and what is
// not.
var recv types.Object
switch obj := obj.(type) {
case *types.Func:
sig := obj.Type().(*types.Signature)
if sig.Recv() != nil {
tname := typeToObject(sig.Recv().Type())
if tname != nil { // beware typed nil
recv = tname
}
}
case *types.Var:
if obj.IsField() {
if spec, ok := spec.(*ast.TypeSpec); ok {
typeName := spec.Name
scopeObj, _ := obj.Pkg().Scope().Lookup(typeName.Name).(*types.TypeName)
if scopeObj != nil {
if st, _ := scopeObj.Type().Underlying().(*types.Struct); st != nil {
for i := 0; i < st.NumFields(); i++ {
if obj == st.Field(i) {
recv = scopeObj
}
}
}
}
}
}
}
// Even if the object is not available in package documentation, it may
// be embedded in a documented receiver. Detect this by searching
// enclosing selector expressions.
//
// TODO(rfindley): pkgsite doesn't document fields from embedding, just
// methods.
if recv == nil || !recv.Exported() {
path := pathEnclosingObjNode(pgf.File, pos)
if enclosing := searchForEnclosing(pkg.TypesInfo(), path); enclosing != nil {
recv = enclosing
} else {
recv = nil // note: just recv = ... could result in a typed nil.
}
}
pkg := obj.Pkg()
if recv != nil {
linkName = fmt.Sprintf("(%s.%s).%s", pkg.Name(), recv.Name(), obj.Name())
if obj.Exported() && recv.Exported() && isPackageLevel(recv) {
linkPath = pkg.Path()
anchor = fmt.Sprintf("%s.%s", recv.Name(), obj.Name())
}
} else {
linkName = fmt.Sprintf("%s.%s", pkg.Name(), obj.Name())
if obj.Exported() && isPackageLevel(obj) {
linkPath = pkg.Path()
anchor = obj.Name()
}
}
}
}
if snapshot.IsGoPrivatePath(linkPath) || linkMeta.ForTest != "" {
linkPath = ""
} else if linkMeta.Module != nil && linkMeta.Module.Version != "" {
mod := linkMeta.Module
linkPath = strings.Replace(linkPath, mod.Path, mod.Path+"@"+mod.Version, 1)
}
var version *stdlib.Version
if symbol := StdSymbolOf(obj); symbol != nil {
version = &symbol.Version
}
return *hoverRange, &hoverJSON{
Synopsis: doc.Synopsis(docText),
FullDocumentation: docText,
SingleLine: singleLineSignature,
SymbolName: linkName,
Signature: signature,
LinkPath: linkPath,
LinkAnchor: anchor,
typeDecl: typeDecl,
methods: methods,
promotedFields: fields,
stdVersion: version,
}, nil
}
// hoverBuiltin computes hover information when hovering over a builtin
// identifier.
func hoverBuiltin(ctx context.Context, snapshot *cache.Snapshot, obj types.Object) (*hoverJSON, error) {
// Special handling for error.Error, which is the only builtin method.
//
// TODO(rfindley): can this be unified with the handling below?
if obj.Name() == "Error" {
signature := obj.String()
return &hoverJSON{
Signature: signature,
SingleLine: signature,
// TODO(rfindley): these are better than the current behavior.
// SymbolName: "(error).Error",
// LinkPath: "builtin",
// LinkAnchor: "error.Error",
}, nil
}
pgf, ident, err := builtinDecl(ctx, snapshot, obj)
if err != nil {
return nil, err
}
var (
comment *ast.CommentGroup
decl ast.Decl
)
path, _ := astutil.PathEnclosingInterval(pgf.File, ident.Pos(), ident.Pos())
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
// Separate documentation and signature.
comment = n.Doc
node2 := *n
node2.Doc = nil
decl = &node2
case *ast.FuncDecl:
// Ditto.
comment = n.Doc
node2 := *n
node2.Doc = nil
decl = &node2
}
}
signature := formatNodeFile(pgf.Tok, decl)
// Replace fake types with their common equivalent.
// TODO(rfindley): we should instead use obj.Type(), which would have the
// *actual* types of the builtin call.
signature = replacer.Replace(signature)
docText := comment.Text()
return &hoverJSON{
Synopsis: doc.Synopsis(docText),
FullDocumentation: docText,
Signature: signature,
SingleLine: obj.String(),
SymbolName: obj.Name(),
LinkPath: "builtin",
LinkAnchor: obj.Name(),
}, nil
}
// hoverImport computes hover information when hovering over the import path of
// imp in the file pgf of pkg.
//
// If we do not have metadata for the hovered import, it returns _
func hoverImport(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, imp *ast.ImportSpec) (protocol.Range, *hoverJSON, error) {
rng, err := pgf.NodeRange(imp.Path)
if err != nil {
return protocol.Range{}, nil, err
}
importPath := metadata.UnquoteImportPath(imp)
if importPath == "" {
return protocol.Range{}, nil, fmt.Errorf("invalid import path")
}
impID := pkg.Metadata().DepsByImpPath[importPath]
if impID == "" {
return protocol.Range{}, nil, fmt.Errorf("no package data for import %q", importPath)
}
impMetadata := snapshot.Metadata(impID)
if impMetadata == nil {
return protocol.Range{}, nil, bug.Errorf("failed to resolve import ID %q", impID)
}
// Find the first file with a package doc comment.
var comment *ast.CommentGroup
for _, f := range impMetadata.CompiledGoFiles {
fh, err := snapshot.ReadFile(ctx, f)
if err != nil {
if ctx.Err() != nil {
return protocol.Range{}, nil, ctx.Err()
}
continue
}
pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header)
if err != nil {
if ctx.Err() != nil {
return protocol.Range{}, nil, ctx.Err()
}
continue
}
if pgf.File.Doc != nil {
comment = pgf.File.Doc
break
}
}
docText := comment.Text()
return rng, &hoverJSON{
Synopsis: doc.Synopsis(docText),
FullDocumentation: docText,
}, nil
}
// hoverPackageName computes hover information for the package name of the file
// pgf in pkg.
func hoverPackageName(pkg *cache.Package, pgf *parsego.File) (protocol.Range, *hoverJSON, error) {
var comment *ast.CommentGroup
for _, pgf := range pkg.CompiledGoFiles() {
if pgf.File.Doc != nil {
comment = pgf.File.Doc
break
}
}
rng, err := pgf.NodeRange(pgf.File.Name)
if err != nil {
return protocol.Range{}, nil, err
}
docText := comment.Text()
return rng, &hoverJSON{
Synopsis: doc.Synopsis(docText),
FullDocumentation: docText,
// Note: including a signature is redundant, since the cursor is already on the
// package name.
}, nil
}
// hoverLit computes hover information when hovering over the basic literal lit
// in the file pgf. The provided pos must be the exact position of the cursor,
// as it is used to extract the hovered rune in strings.
//
// For example, hovering over "\u2211" in "foo \u2211 bar" yields:
//
// '∑', U+2211, N-ARY SUMMATION
func hoverLit(pgf *parsego.File, lit *ast.BasicLit, pos token.Pos) (protocol.Range, *hoverJSON, error) {
var (
value string // if non-empty, a constant value to format in hover
r rune // if non-zero, format a description of this rune in hover
start, end token.Pos // hover span
)
// Extract a rune from the current position.
// 'Ω', "...Ω...", or 0x03A9 => 'Ω', U+03A9, GREEK CAPITAL LETTER OMEGA
switch lit.Kind {
case token.CHAR:
s, err := strconv.Unquote(lit.Value)
if err != nil {
// If the conversion fails, it's because of an invalid syntax, therefore
// there is no rune to be found.
return protocol.Range{}, nil, nil
}
r, _ = utf8.DecodeRuneInString(s)
if r == utf8.RuneError {
return protocol.Range{}, nil, fmt.Errorf("rune error")
}
start, end = lit.Pos(), lit.End()
case token.INT:
// Short literals (e.g. 99 decimal, 07 octal) are uninteresting.
if len(lit.Value) < 3 {
return protocol.Range{}, nil, nil
}
v := constant.MakeFromLiteral(lit.Value, lit.Kind, 0)
if v.Kind() != constant.Int {
return protocol.Range{}, nil, nil
}
switch lit.Value[:2] {
case "0x", "0X":
// As a special case, try to recognize hexadecimal literals as runes if
// they are within the range of valid unicode values.
if v, ok := constant.Int64Val(v); ok && v > 0 && v <= utf8.MaxRune && utf8.ValidRune(rune(v)) {
r = rune(v)
}
fallthrough
case "0o", "0O", "0b", "0B":
// Format the decimal value of non-decimal literals.
value = v.ExactString()
start, end = lit.Pos(), lit.End()
default:
return protocol.Range{}, nil, nil
}
case token.STRING:
// It's a string, scan only if it contains a unicode escape sequence under or before the
// current cursor position.
litOffset, err := safetoken.Offset(pgf.Tok, lit.Pos())
if err != nil {
return protocol.Range{}, nil, err
}
offset, err := safetoken.Offset(pgf.Tok, pos)
if err != nil {
return protocol.Range{}, nil, err
}
for i := offset - litOffset; i > 0; i-- {
// Start at the cursor position and search backward for the beginning of a rune escape sequence.
rr, _ := utf8.DecodeRuneInString(lit.Value[i:])
if rr == utf8.RuneError {
return protocol.Range{}, nil, fmt.Errorf("rune error")
}
if rr == '\\' {
// Got the beginning, decode it.
var tail string
r, _, tail, err = strconv.UnquoteChar(lit.Value[i:], '"')
if err != nil {
// If the conversion fails, it's because of an invalid syntax,
// therefore is no rune to be found.
return protocol.Range{}, nil, nil
}
// Only the rune escape sequence part of the string has to be highlighted, recompute the range.
runeLen := len(lit.Value) - (i + len(tail))
start = token.Pos(int(lit.Pos()) + i)
end = token.Pos(int(start) + runeLen)
break
}
}
}
if value == "" && r == 0 { // nothing to format
return protocol.Range{}, nil, nil
}
rng, err := pgf.PosRange(start, end)
if err != nil {
return protocol.Range{}, nil, err
}
var b strings.Builder
if value != "" {
b.WriteString(value)
}
if r != 0 {
runeName := runenames.Name(r)
if len(runeName) > 0 && runeName[0] == '<' {
// Check if the rune looks like an HTML tag. If so, trim the surrounding <>
// characters to work around https://github.com/microsoft/vscode/issues/124042.
runeName = strings.TrimRight(runeName[1:], ">")
}
if b.Len() > 0 {
b.WriteString(", ")
}
if strconv.IsPrint(r) {
fmt.Fprintf(&b, "'%c', ", r)
}
fmt.Fprintf(&b, "U+%04X, %s", r, runeName)
}
hover := b.String()
return rng, &hoverJSON{
Synopsis: hover,
FullDocumentation: hover,
}, nil
}
// hoverEmbed computes hover information for a filepath.Match pattern.
// Assumes that the pattern is relative to the location of fh.
func hoverEmbed(fh file.Handle, rng protocol.Range, pattern string) (protocol.Range, *hoverJSON, error) {
s := &strings.Builder{}
dir := filepath.Dir(fh.URI().Path())
var matches []string
err := filepath.WalkDir(dir, func(abs string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
rel, err := filepath.Rel(dir, abs)
if err != nil {
return err
}
ok, err := filepath.Match(pattern, rel)
if err != nil {
return err
}
if ok && !d.IsDir() {
matches = append(matches, rel)
}
return nil
})
if err != nil {
return protocol.Range{}, nil, err
}
for _, m := range matches {
// TODO: Renders each file as separate markdown paragraphs.
// If forcing (a single) newline is possible it might be more clear.
fmt.Fprintf(s, "%s\n\n", m)
}
json := &hoverJSON{
Signature: fmt.Sprintf("Embedding %q", pattern),
Synopsis: s.String(),
FullDocumentation: s.String(),
}
return rng, json, nil
}
// inferredSignatureString is a wrapper around the types.ObjectString function
// that adds more information to inferred signatures. It will return an empty string
// if the passed types.Object is not a signature.
func inferredSignatureString(obj types.Object, qf types.Qualifier, inferred *types.Signature) string {
// If the signature type was inferred, prefer the inferred signature with a
// comment showing the generic signature.
if sig, _ := obj.Type().Underlying().(*types.Signature); sig != nil && sig.TypeParams().Len() > 0 && inferred != nil {
obj2 := types.NewFunc(obj.Pos(), obj.Pkg(), obj.Name(), inferred)
str := types.ObjectString(obj2, qf)
// Try to avoid overly long lines.
if len(str) > 60 {
str += "\n"
} else {
str += " "
}
str += "// " + types.TypeString(sig, qf)
return str
}
return ""
}
// objectString is a wrapper around the types.ObjectString function.
// It handles adding more information to the object string.
// If spec is non-nil, it may be used to format additional declaration
// syntax, and file must be the token.File describing its positions.
//
// Precondition: obj is not a built-in function or method.
func objectString(obj types.Object, qf types.Qualifier, declPos token.Pos, file *token.File, spec ast.Spec) string {
str := types.ObjectString(obj, qf)
switch obj := obj.(type) {
case *types.Func:
// We fork ObjectString to improve its rendering of methods:
// specifically, we show the receiver name,
// and replace the period in (T).f by a space (#62190).
sig := obj.Type().(*types.Signature)
var buf bytes.Buffer
buf.WriteString("func ")
if recv := sig.Recv(); recv != nil {
buf.WriteByte('(')
if _, ok := recv.Type().(*types.Interface); ok {
// gcimporter creates abstract methods of
// named interfaces using the interface type
// (not the named type) as the receiver.
// Don't print it in full.
buf.WriteString("interface")
} else {
// Show receiver name (go/types does not).
name := recv.Name()
if name != "" && name != "_" {
buf.WriteString(name)
buf.WriteString(" ")
}
types.WriteType(&buf, recv.Type(), qf)
}
buf.WriteByte(')')
buf.WriteByte(' ') // space (go/types uses a period)
} else if s := qf(obj.Pkg()); s != "" {
buf.WriteString(s)
buf.WriteString(".")
}
buf.WriteString(obj.Name())
types.WriteSignature(&buf, sig, qf)
str = buf.String()
case *types.Const:
// Show value of a constant.
var (
declaration = obj.Val().String() // default formatted declaration
comment = "" // if non-empty, a clarifying comment
)
// Try to use the original declaration.
switch obj.Val().Kind() {
case constant.String:
// Usually the original declaration of a string doesn't carry much information.
// Also strings can be very long. So, just use the constant's value.
default:
if spec, _ := spec.(*ast.ValueSpec); spec != nil {
for i, name := range spec.Names {
if declPos == name.Pos() {
if i < len(spec.Values) {
originalDeclaration := formatNodeFile(file, spec.Values[i])
if originalDeclaration != declaration {
comment = declaration
declaration = originalDeclaration
}
}
break
}
}
}
}
// Special formatting cases.
switch typ := aliases.Unalias(obj.Type()).(type) {
case *types.Named:
// Try to add a formatted duration as an inline comment.
pkg := typ.Obj().Pkg()
if pkg.Path() == "time" && typ.Obj().Name() == "Duration" && obj.Val().Kind() == constant.Int {
if d, ok := constant.Int64Val(obj.Val()); ok {
comment = time.Duration(d).String()
}
}
}
if comment == declaration {
comment = ""
}
str += " = " + declaration
if comment != "" {
str += " // " + comment
}
}
return str
}
// 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 HoverDocForObject(ctx context.Context, snapshot *cache.Snapshot, fset *token.FileSet, obj types.Object) (*ast.CommentGroup, error) {
if is[*types.TypeName](obj) && is[*types.TypeParam](obj.Type()) {
return nil, nil
}
pgf, pos, err := parseFull(ctx, snapshot, fset, obj.Pos())
if err != nil {
return nil, fmt.Errorf("re-parsing: %v", err)
}
decl, spec, field := findDeclInfo([]*ast.File{pgf.File}, pos)
return chooseDocComment(decl, spec, field), nil
}
func chooseDocComment(decl ast.Decl, spec ast.Spec, field *ast.Field) *ast.CommentGroup {
if field != nil {
if field.Doc != nil {
return field.Doc
}
if field.Comment != nil {
return field.Comment
}
return nil
}
switch decl := decl.(type) {
case *ast.FuncDecl:
return decl.Doc
case *ast.GenDecl:
switch spec := spec.(type) {
case *ast.ValueSpec:
if spec.Doc != nil {
return spec.Doc
}
if decl.Doc != nil {
return decl.Doc
}
return spec.Comment
case *ast.TypeSpec:
if spec.Doc != nil {
return spec.Doc
}
if decl.Doc != nil {
return decl.Doc
}
return spec.Comment
}
}
return nil
}
// parseFull fully parses the file corresponding to position pos (for
// which fset provides file/line information).
//
// It returns the resulting parsego.File as well as new pos contained
// in the parsed file.
//
// BEWARE: the provided FileSet is used only to interpret the provided
// pos; the resulting File and Pos may belong to the same or a
// different FileSet, such as one synthesized by the parser cache, if
// parse-caching is enabled.
func parseFull(ctx context.Context, snapshot *cache.Snapshot, fset *token.FileSet, pos token.Pos) (*parsego.File, token.Pos, error) {
f := fset.File(pos)
if f == nil {
return nil, 0, bug.Errorf("internal error: no file for position %d", pos)
}
uri := protocol.URIFromPath(f.Name())
fh, err := snapshot.ReadFile(ctx, uri)
if err != nil {
return nil, 0, err
}
pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
if err != nil {
return nil, 0, err
}
offset, err := safetoken.Offset(f, pos)
if err != nil {
return nil, 0, bug.Errorf("offset out of bounds in %q", uri)
}
fullPos, err := safetoken.Pos(pgf.Tok, offset)
if err != nil {
return nil, 0, err
}
return pgf, fullPos, nil
}
// If pkgURL is non-nil, it should be used to generate doc links.
func formatHover(h *hoverJSON, options *settings.Options, pkgURL func(path PackagePath, fragment string) protocol.URI) (string, error) {
maybeMarkdown := func(s string) string {
if s != "" && options.PreferredContentFormat == protocol.Markdown {
s = fmt.Sprintf("```go\n%s\n```", strings.Trim(s, "\n"))
}
return s
}
switch options.HoverKind {
case settings.SingleLine:
return h.SingleLine, nil
case settings.NoDocumentation:
return maybeMarkdown(h.Signature), nil
case settings.Structured:
b, err := json.Marshal(h)
if err != nil {
return "", err
}
return string(b), nil
case settings.SynopsisDocumentation,
settings.FullDocumentation:
// For types, we display TypeDecl and Methods,
// but not Signature, which is redundant (= TypeDecl + "\n" + Methods).
// For all other symbols, we display Signature;
// TypeDecl and Methods are empty.
// (This awkwardness is to preserve JSON compatibility.)
parts := []string{
maybeMarkdown(h.Signature),
maybeMarkdown(h.typeDecl),
formatDoc(h, options),
maybeMarkdown(h.promotedFields),
maybeMarkdown(h.methods),
fmt.Sprintf("Added in %v", h.stdVersion),
formatLink(h, options, pkgURL),
}
if h.typeDecl != "" {
parts[0] = "" // type: suppress redundant Signature
}
if h.stdVersion == nil || *h.stdVersion == stdlib.Version(0) {
parts[5] = "" // suppress stdlib version if not applicable or initial version 1.0
}
parts = slices.Remove(parts, "")
var b strings.Builder
for i, part := range parts {
if i > 0 {
if options.PreferredContentFormat == protocol.Markdown {
b.WriteString("\n\n")
} else {
b.WriteByte('\n')
}
}
b.WriteString(part)
}
return b.String(), nil
default:
return "", fmt.Errorf("invalid HoverKind: %v", options.HoverKind)
}
}
// StdSymbolOf returns the std lib symbol information of the given obj.
// It returns nil if the input obj is not an exported standard library symbol.
func StdSymbolOf(obj types.Object) *stdlib.Symbol {
if !obj.Exported() || obj.Pkg() == nil {
return nil
}
// Symbols that not defined in standard library should return early.
// TODO(hxjiang): The returned slices is binary searchable.
symbols := stdlib.PackageSymbols[obj.Pkg().Path()]
if symbols == nil {
return nil
}
// Handle Function, Type, Const & Var.
if isPackageLevel(obj) {
for _, s := range symbols {
if s.Kind == stdlib.Method || s.Kind == stdlib.Field {
continue
}
if s.Name == obj.Name() {
return &s
}
}
return nil
}
// Handle Method.
if fn, _ := obj.(*types.Func); fn != nil {
isPtr, named := typesinternal.ReceiverNamed(fn.Type().(*types.Signature).Recv())
if isPackageLevel(named.Obj()) {
for _, s := range symbols {
if s.Kind != stdlib.Method {
continue
}
ptr, recv, name := s.SplitMethod()
if ptr == isPtr && recv == named.Obj().Name() && name == fn.Name() {
return &s
}
}
return nil
}
}
// Handle Field.
if v, _ := obj.(*types.Var); v != nil && v.IsField() {
for _, s := range symbols {
if s.Kind != stdlib.Field {
continue
}
typeName, fieldName := s.SplitField()
if fieldName != v.Name() {
continue
}
typeObj := obj.Pkg().Scope().Lookup(typeName)
if typeObj == nil {
continue
}
if fieldObj, _, _ := types.LookupFieldOrMethod(typeObj.Type(), true, obj.Pkg(), fieldName); obj == fieldObj {
return &s
}
}
return nil
}
return nil
}
// If pkgURL is non-nil, it should be used to generate doc links.
func formatLink(h *hoverJSON, options *settings.Options, pkgURL func(path PackagePath, fragment string) protocol.URI) string {
if options.LinksInHover == false || h.LinkPath == "" {
return ""
}
var url protocol.URI
var caption string
if pkgURL != nil { // LinksInHover == "gopls"
path, _, _ := strings.Cut(h.LinkPath, "@") // remove optional module version suffix
url = pkgURL(PackagePath(path), h.LinkAnchor)
caption = "in gopls doc viewer"
} else {
if options.LinkTarget == "" {
return ""
}
url = cache.BuildLink(options.LinkTarget, h.LinkPath, h.LinkAnchor)
caption = "on " + options.LinkTarget
}
switch options.PreferredContentFormat {
case protocol.Markdown:
return fmt.Sprintf("[`%s` %s](%s)", h.SymbolName, caption, url)
case protocol.PlainText:
return ""
default:
return url
}
}
func formatDoc(h *hoverJSON, options *settings.Options) string {
var doc string
switch options.HoverKind {
case settings.SynopsisDocumentation:
doc = h.Synopsis
case settings.FullDocumentation:
doc = h.FullDocumentation
}
if options.PreferredContentFormat == protocol.Markdown {
return CommentToMarkdown(doc, options)
}
return doc
}
// findDeclInfo returns the syntax nodes involved in the declaration of the
// types.Object with position pos, searching the given list of file syntax
// trees.
//
// Pos may be the position of the name-defining identifier in a FuncDecl,
// ValueSpec, TypeSpec, Field, or as a special case the position of
// Ellipsis.Elt in an ellipsis field.
//
// If found, the resulting decl, spec, and field will be the inner-most
// instance of each node type surrounding pos.
//
// If field is non-nil, pos is the position of a field Var. If field is nil and
// spec is non-nil, pos is the position of a Var, Const, or TypeName object. If
// both field and spec are nil and decl is non-nil, pos is the position of a
// Func object.
//
// It returns a nil decl if no object-defining node is found at pos.
//
// TODO(rfindley): this function has tricky semantics, and may be worth unit
// testing and/or refactoring.
func findDeclInfo(files []*ast.File, pos token.Pos) (decl ast.Decl, spec ast.Spec, field *ast.Field) {
found := false
// Visit the files in search of the node at pos.
stack := make([]ast.Node, 0, 20)
// Allocate the closure once, outside the loop.
f := func(n ast.Node) bool {
if found {
return false
}
if n != nil {
stack = append(stack, n) // push
} else {
stack = stack[:len(stack)-1] // pop
return false
}
// Skip subtrees (incl. files) that don't contain the search point.
if !(n.Pos() <= pos && pos < n.End()) {
return false
}
switch n := n.(type) {
case *ast.Field:
findEnclosingDeclAndSpec := func() {
for i := len(stack) - 1; i >= 0; i-- {
switch n := stack[i].(type) {
case ast.Spec:
spec = n
case ast.Decl:
decl = n
return
}
}
}
// Check each field name since you can have
// multiple names for the same type expression.
for _, id := range n.Names {
if id.Pos() == pos {
field = n
findEnclosingDeclAndSpec()
found = true
return false
}
}
// Check *ast.Field itself. This handles embedded
// fields which have no associated *ast.Ident name.
if n.Pos() == pos {
field = n
findEnclosingDeclAndSpec()
found = true
return false
}
// Also check "X" in "...X". This makes it easy to format variadic
// signature params properly.
//
// TODO(rfindley): I don't understand this comment. How does finding the
// field in this case make it easier to format variadic signature params?
if ell, ok := n.Type.(*ast.Ellipsis); ok && ell.Elt != nil && ell.Elt.Pos() == pos {
field = n
findEnclosingDeclAndSpec()
found = true
return false
}
case *ast.FuncDecl:
if n.Name.Pos() == pos {
decl = n
found = true
return false
}
case *ast.GenDecl:
for _, s := range n.Specs {
switch s := s.(type) {
case *ast.TypeSpec:
if s.Name.Pos() == pos {
decl = n
spec = s
found = true
return false
}
case *ast.ValueSpec:
for _, id := range s.Names {
if id.Pos() == pos {
decl = n
spec = s
found = true
return false
}
}
}
}
}
return true
}
for _, file := range files {
ast.Inspect(file, f)
if found {
return decl, spec, field
}
}
return nil, nil, nil
}
type promotedField struct {
path string // path (e.g. "x.y" through embedded fields)
field *types.Var
}
// promotedFields returns the list of accessible promoted fields of a struct type t.
// (Logic plundered from x/tools/cmd/guru/describe.go.)
func promotedFields(t types.Type, from *types.Package) []promotedField {
wantField := func(f *types.Var) bool {
if !accessibleTo(f, from) {
return false
}
// Check that the field is not shadowed.
obj, _, _ := types.LookupFieldOrMethod(t, true, f.Pkg(), f.Name())
return obj == f
}
var fields []promotedField
var visit func(t types.Type, stack []*types.Named)
visit = func(t types.Type, stack []*types.Named) {
tStruct, ok := typesinternal.Unpointer(t).Underlying().(*types.Struct)
if !ok {
return
}
fieldloop:
for i := 0; i < tStruct.NumFields(); i++ {
f := tStruct.Field(i)
// Handle recursion through anonymous fields.
if f.Anonymous() {
if _, named := typesinternal.ReceiverNamed(f); named != nil {
// If we've already visited this named type
// on this path, break the cycle.
for _, x := range stack {
if x.Origin() == named.Origin() {
continue fieldloop
}
}
visit(f.Type(), append(stack, named))
}
}
// Save accessible promoted fields.
if len(stack) > 0 && wantField(f) {
var path strings.Builder
for i, t := range stack {
if i > 0 {
path.WriteByte('.')
}
path.WriteString(t.Obj().Name())
}
fields = append(fields, promotedField{
path: path.String(),
field: f,
})
}
}
}
visit(t, nil)
return fields
}
func accessibleTo(obj types.Object, pkg *types.Package) bool {
return obj.Exported() || obj.Pkg() == pkg
}
// computeSizeOffsetInfo reports the size of obj (if a type or struct
// field), its wasted space percentage (if a struct type), and its
// offset (if a struct field). It returns -1 for undefined components.
func computeSizeOffsetInfo(pkg *cache.Package, path []ast.Node, obj types.Object) (size, wasted, offset int64) {
size, wasted, offset = -1, -1, -1
var free typeparams.Free
sizes := pkg.TypesSizes()
// size (types and fields)
if v, ok := obj.(*types.Var); ok && v.IsField() || is[*types.TypeName](obj) {
// If the field's type has free type parameters,
// its size cannot be computed.
if !free.Has(obj.Type()) {
size = sizes.Sizeof(obj.Type())
}
// wasted space (struct types)
if tStruct, ok := obj.Type().Underlying().(*types.Struct); ok && is[*types.TypeName](obj) && size > 0 {
var fields []*types.Var
for i := 0; i < tStruct.NumFields(); i++ {
fields = append(fields, tStruct.Field(i))
}
if len(fields) > 0 {
// Sort into descending (most compact) order
// and recompute size of entire struct.
sort.Slice(fields, func(i, j int) bool {
return sizes.Sizeof(fields[i].Type()) >
sizes.Sizeof(fields[j].Type())
})
offsets := sizes.Offsetsof(fields)
compactSize := offsets[len(offsets)-1] + sizes.Sizeof(fields[len(fields)-1].Type())
wasted = 100 * (size - compactSize) / size
}
}
}
// offset (fields)
if v, ok := obj.(*types.Var); ok && v.IsField() {
// Find enclosing struct type.
var tStruct *types.Struct
for _, n := range path {
if n, ok := n.(*ast.StructType); ok {
tStruct = pkg.TypesInfo().TypeOf(n).(*types.Struct)
break
}
}
if tStruct != nil {
var fields []*types.Var
for i := 0; i < tStruct.NumFields(); i++ {
f := tStruct.Field(i)
// If any preceding field's type has free type parameters,
// its offset cannot be computed.
if free.Has(f.Type()) {
break
}
fields = append(fields, f)
if f == v {
offsets := sizes.Offsetsof(fields)
offset = offsets[len(offsets)-1]
break
}
}
}
}
return
}
| tools/gopls/internal/golang/hover.go/0 | {
"file_path": "tools/gopls/internal/golang/hover.go",
"repo_id": "tools",
"token_count": 17778
} | 741 |
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
// This file defines the Semantic Tokens operation for Go source.
import (
"bytes"
"context"
"errors"
"fmt"
"go/ast"
"go/token"
"go/types"
"log"
"path/filepath"
"regexp"
"strings"
"time"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/cache/metadata"
"golang.org/x/tools/gopls/internal/cache/parsego"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/protocol/semtok"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/gopls/internal/util/safetoken"
"golang.org/x/tools/gopls/internal/util/typesutil"
"golang.org/x/tools/internal/aliases"
"golang.org/x/tools/internal/event"
)
// semDebug enables comprehensive logging of decisions
// (gopls semtok foo.go > /dev/null shows log output).
// It should never be true in checked-in code.
const semDebug = false
func SemanticTokens(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng *protocol.Range) (*protocol.SemanticTokens, error) {
pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
if err != nil {
return nil, err
}
// Select range.
var start, end token.Pos
if rng != nil {
var err error
start, end, err = pgf.RangePos(*rng)
if err != nil {
return nil, err // e.g. invalid range
}
} else {
tok := pgf.Tok
start, end = tok.Pos(0), tok.Pos(tok.Size()) // entire file
}
// Reject full semantic token requests for large files.
//
// The LSP says that errors for the semantic token requests
// should only be returned for exceptions (a word not
// otherwise defined). This code treats a too-large file as an
// exception. On parse errors, the code does what it can.
const maxFullFileSize = 100000
if int(end-start) > maxFullFileSize {
return nil, fmt.Errorf("semantic tokens: range %s too large (%d > %d)",
fh.URI().Path(), end-start, maxFullFileSize)
}
tv := tokenVisitor{
ctx: ctx,
metadataSource: snapshot,
metadata: pkg.Metadata(),
info: pkg.TypesInfo(),
fset: pkg.FileSet(),
pkg: pkg,
pgf: pgf,
start: start,
end: end,
}
tv.visit()
return &protocol.SemanticTokens{
Data: semtok.Encode(
tv.tokens,
snapshot.Options().NoSemanticString,
snapshot.Options().NoSemanticNumber,
snapshot.Options().SemanticTypes,
snapshot.Options().SemanticMods),
ResultID: time.Now().String(), // for delta requests, but we've never seen any
}, nil
}
type tokenVisitor struct {
// inputs
ctx context.Context // for event logging
metadataSource metadata.Source // used to resolve imports
metadata *metadata.Package
info *types.Info
fset *token.FileSet
pkg *cache.Package
pgf *parsego.File
start, end token.Pos // range of interest
// working state
stack []ast.Node // path from root of the syntax tree
tokens []semtok.Token // computed sequence of semantic tokens
}
func (tv *tokenVisitor) visit() {
f := tv.pgf.File
// may not be in range, but harmless
tv.token(f.Package, len("package"), semtok.TokKeyword, nil)
if f.Name != nil {
tv.token(f.Name.NamePos, len(f.Name.Name), semtok.TokNamespace, nil)
}
for _, decl := range f.Decls {
// Only look at the decls that overlap the range.
if decl.End() <= tv.start || decl.Pos() >= tv.end {
continue
}
ast.Inspect(decl, tv.inspect)
}
// Scan all files for imported pkgs, ignore the ambiguous pkg.
// This is to be consistent with the behavior in [go/doc]: https://pkg.go.dev/pkg/go/doc.
importByName := make(map[string]*types.PkgName)
for _, pgf := range tv.pkg.CompiledGoFiles() {
for _, imp := range pgf.File.Imports {
if obj, _ := typesutil.ImportedPkgName(tv.pkg.TypesInfo(), imp); obj != nil {
if old, ok := importByName[obj.Name()]; ok {
if old != nil && old.Imported() != obj.Imported() {
importByName[obj.Name()] = nil // nil => ambiguous across files
}
continue
}
importByName[obj.Name()] = obj
}
}
}
for _, cg := range f.Comments {
for _, c := range cg.List {
// Only look at the comment that overlap the range.
if c.End() <= tv.start || c.Pos() >= tv.end {
continue
}
tv.comment(c, importByName)
}
}
}
// Matches (for example) "[F]", "[*p.T]", "[p.T.M]"
// unless followed by a colon (exclude url link, e.g. "[go]: https://go.dev").
// The first group is reference name. e.g. The first group of "[*p.T.M]" is "p.T.M".
var docLinkRegex = regexp.MustCompile(`\[\*?([\pL_][\pL_0-9]*(\.[\pL_][\pL_0-9]*){0,2})](?:[^:]|$)`)
// comment emits semantic tokens for a comment.
// If the comment contains doc links or "go:" directives,
// it emits a separate token for each link or directive and
// each comment portion between them.
func (tv *tokenVisitor) comment(c *ast.Comment, importByName map[string]*types.PkgName) {
if strings.HasPrefix(c.Text, "//go:") {
tv.godirective(c)
return
}
pkgScope := tv.pkg.Types().Scope()
// lookupObjects interprets the name in various forms
// (X, p.T, p.T.M, etc) and return the list of symbols
// denoted by each identifier in the dotted list.
lookupObjects := func(name string) (objs []types.Object) {
scope := pkgScope
if pkg, suffix, ok := strings.Cut(name, "."); ok {
if obj, _ := importByName[pkg]; obj != nil {
objs = append(objs, obj)
scope = obj.Imported().Scope()
name = suffix
}
}
if recv, method, ok := strings.Cut(name, "."); ok {
obj, ok := scope.Lookup(recv).(*types.TypeName)
if !ok {
return nil
}
objs = append(objs, obj)
t, ok := obj.Type().(*types.Named)
if !ok {
return nil
}
m, _, _ := types.LookupFieldOrMethod(t, true, tv.pkg.Types(), method)
if m == nil {
return nil
}
objs = append(objs, m)
return objs
} else {
obj := scope.Lookup(name)
if obj == nil {
return nil
}
if _, ok := obj.(*types.PkgName); !ok && !obj.Exported() {
return nil
}
objs = append(objs, obj)
return objs
}
}
tokenTypeByObject := func(obj types.Object) semtok.TokenType {
switch obj.(type) {
case *types.PkgName:
return semtok.TokNamespace
case *types.Func:
return semtok.TokFunction
case *types.TypeName:
return semtok.TokType
case *types.Const, *types.Var:
return semtok.TokVariable
default:
return semtok.TokComment
}
}
pos := c.Pos()
for _, line := range strings.Split(c.Text, "\n") {
last := 0
for _, idx := range docLinkRegex.FindAllStringSubmatchIndex(line, -1) {
// The first group is the reference name. e.g. "X", "p.T", "p.T.M".
name := line[idx[2]:idx[3]]
if objs := lookupObjects(name); len(objs) > 0 {
if last < idx[2] {
tv.token(pos+token.Pos(last), idx[2]-last, semtok.TokComment, nil)
}
offset := pos + token.Pos(idx[2])
for i, obj := range objs {
if i > 0 {
tv.token(offset, len("."), semtok.TokComment, nil)
offset += token.Pos(len("."))
}
id, rest, _ := strings.Cut(name, ".")
name = rest
tv.token(offset, len(id), tokenTypeByObject(obj), nil)
offset += token.Pos(len(id))
}
last = idx[3]
}
}
if last != len(c.Text) {
tv.token(pos+token.Pos(last), len(line)-last, semtok.TokComment, nil)
}
pos += token.Pos(len(line) + 1)
}
}
// token emits a token of the specified extent and semantics.
func (tv *tokenVisitor) token(start token.Pos, length int, typ semtok.TokenType, modifiers []string) {
if !start.IsValid() {
return
}
if length <= 0 {
return // vscode doesn't like 0-length Tokens
}
end := start + token.Pos(length)
if start >= tv.end || end <= tv.start {
return
}
// want a line and column from start (in LSP coordinates). Ignore line directives.
rng, err := tv.pgf.PosRange(start, end)
if err != nil {
event.Error(tv.ctx, "failed to convert to range", err)
return
}
if rng.End.Line != rng.Start.Line {
// this happens if users are typing at the end of the file, but report nothing
return
}
tv.tokens = append(tv.tokens, semtok.Token{
Line: rng.Start.Line,
Start: rng.Start.Character,
Len: rng.End.Character - rng.Start.Character, // (on same line)
Type: typ,
Modifiers: modifiers,
})
}
// strStack converts the stack to a string, for debugging and error messages.
func (tv *tokenVisitor) strStack() string {
msg := []string{"["}
for i := len(tv.stack) - 1; i >= 0; i-- {
n := tv.stack[i]
msg = append(msg, strings.TrimPrefix(fmt.Sprintf("%T", n), "*ast."))
}
if len(tv.stack) > 0 {
pos := tv.stack[len(tv.stack)-1].Pos()
if _, err := safetoken.Offset(tv.pgf.Tok, pos); err != nil {
msg = append(msg, fmt.Sprintf("invalid position %v for %s", pos, tv.pgf.URI))
} else {
posn := safetoken.Position(tv.pgf.Tok, pos)
msg = append(msg, fmt.Sprintf("(%s:%d,col:%d)",
filepath.Base(posn.Filename), posn.Line, posn.Column))
}
}
msg = append(msg, "]")
return strings.Join(msg, " ")
}
// srcLine returns the source text for n (truncated at first newline).
func (tv *tokenVisitor) srcLine(n ast.Node) string {
file := tv.pgf.Tok
line := safetoken.Line(file, n.Pos())
start, err := safetoken.Offset(file, file.LineStart(line))
if err != nil {
return ""
}
end := start
for ; end < len(tv.pgf.Src) && tv.pgf.Src[end] != '\n'; end++ {
}
return string(tv.pgf.Src[start:end])
}
func (tv *tokenVisitor) inspect(n ast.Node) (descend bool) {
if n == nil {
tv.stack = tv.stack[:len(tv.stack)-1] // pop
return true
}
tv.stack = append(tv.stack, n) // push
defer func() {
if !descend {
tv.stack = tv.stack[:len(tv.stack)-1] // pop
}
}()
switch n := n.(type) {
case *ast.ArrayType:
case *ast.AssignStmt:
tv.token(n.TokPos, len(n.Tok.String()), semtok.TokOperator, nil)
case *ast.BasicLit:
if strings.Contains(n.Value, "\n") {
// has to be a string.
tv.multiline(n.Pos(), n.End(), semtok.TokString)
break
}
what := semtok.TokNumber
if n.Kind == token.STRING {
what = semtok.TokString
}
tv.token(n.Pos(), len(n.Value), what, nil)
case *ast.BinaryExpr:
tv.token(n.OpPos, len(n.Op.String()), semtok.TokOperator, nil)
case *ast.BlockStmt:
case *ast.BranchStmt:
tv.token(n.TokPos, len(n.Tok.String()), semtok.TokKeyword, nil)
if n.Label != nil {
tv.token(n.Label.Pos(), len(n.Label.Name), semtok.TokLabel, nil)
}
case *ast.CallExpr:
if n.Ellipsis.IsValid() {
tv.token(n.Ellipsis, len("..."), semtok.TokOperator, nil)
}
case *ast.CaseClause:
iam := "case"
if n.List == nil {
iam = "default"
}
tv.token(n.Case, len(iam), semtok.TokKeyword, nil)
case *ast.ChanType:
// chan | chan <- | <- chan
switch {
case n.Arrow == token.NoPos:
tv.token(n.Begin, len("chan"), semtok.TokKeyword, nil)
case n.Arrow == n.Begin:
tv.token(n.Arrow, 2, semtok.TokOperator, nil)
pos := tv.findKeyword("chan", n.Begin+2, n.Value.Pos())
tv.token(pos, len("chan"), semtok.TokKeyword, nil)
case n.Arrow != n.Begin:
tv.token(n.Begin, len("chan"), semtok.TokKeyword, nil)
tv.token(n.Arrow, 2, semtok.TokOperator, nil)
}
case *ast.CommClause:
length := len("case")
if n.Comm == nil {
length = len("default")
}
tv.token(n.Case, length, semtok.TokKeyword, nil)
case *ast.CompositeLit:
case *ast.DeclStmt:
case *ast.DeferStmt:
tv.token(n.Defer, len("defer"), semtok.TokKeyword, nil)
case *ast.Ellipsis:
tv.token(n.Ellipsis, len("..."), semtok.TokOperator, nil)
case *ast.EmptyStmt:
case *ast.ExprStmt:
case *ast.Field:
case *ast.FieldList:
case *ast.ForStmt:
tv.token(n.For, len("for"), semtok.TokKeyword, nil)
case *ast.FuncDecl:
case *ast.FuncLit:
case *ast.FuncType:
if n.Func != token.NoPos {
tv.token(n.Func, len("func"), semtok.TokKeyword, nil)
}
case *ast.GenDecl:
tv.token(n.TokPos, len(n.Tok.String()), semtok.TokKeyword, nil)
case *ast.GoStmt:
tv.token(n.Go, len("go"), semtok.TokKeyword, nil)
case *ast.Ident:
tv.ident(n)
case *ast.IfStmt:
tv.token(n.If, len("if"), semtok.TokKeyword, nil)
if n.Else != nil {
// x.Body.End() or x.Body.End()+1, not that it matters
pos := tv.findKeyword("else", n.Body.End(), n.Else.Pos())
tv.token(pos, len("else"), semtok.TokKeyword, nil)
}
case *ast.ImportSpec:
tv.importSpec(n)
return false
case *ast.IncDecStmt:
tv.token(n.TokPos, len(n.Tok.String()), semtok.TokOperator, nil)
case *ast.IndexExpr:
case *ast.IndexListExpr:
case *ast.InterfaceType:
tv.token(n.Interface, len("interface"), semtok.TokKeyword, nil)
case *ast.KeyValueExpr:
case *ast.LabeledStmt:
tv.token(n.Label.Pos(), len(n.Label.Name), semtok.TokLabel, []string{"definition"})
case *ast.MapType:
tv.token(n.Map, len("map"), semtok.TokKeyword, nil)
case *ast.ParenExpr:
case *ast.RangeStmt:
tv.token(n.For, len("for"), semtok.TokKeyword, nil)
// x.TokPos == token.NoPos is legal (for range foo {})
offset := n.TokPos
if offset == token.NoPos {
offset = n.For
}
pos := tv.findKeyword("range", offset, n.X.Pos())
tv.token(pos, len("range"), semtok.TokKeyword, nil)
case *ast.ReturnStmt:
tv.token(n.Return, len("return"), semtok.TokKeyword, nil)
case *ast.SelectStmt:
tv.token(n.Select, len("select"), semtok.TokKeyword, nil)
case *ast.SelectorExpr:
case *ast.SendStmt:
tv.token(n.Arrow, len("<-"), semtok.TokOperator, nil)
case *ast.SliceExpr:
case *ast.StarExpr:
tv.token(n.Star, len("*"), semtok.TokOperator, nil)
case *ast.StructType:
tv.token(n.Struct, len("struct"), semtok.TokKeyword, nil)
case *ast.SwitchStmt:
tv.token(n.Switch, len("switch"), semtok.TokKeyword, nil)
case *ast.TypeAssertExpr:
if n.Type == nil {
pos := tv.findKeyword("type", n.Lparen, n.Rparen)
tv.token(pos, len("type"), semtok.TokKeyword, nil)
}
case *ast.TypeSpec:
case *ast.TypeSwitchStmt:
tv.token(n.Switch, len("switch"), semtok.TokKeyword, nil)
case *ast.UnaryExpr:
tv.token(n.OpPos, len(n.Op.String()), semtok.TokOperator, nil)
case *ast.ValueSpec:
// things only seen with parsing or type errors, so ignore them
case *ast.BadDecl, *ast.BadExpr, *ast.BadStmt:
return false
// not going to see these
case *ast.File, *ast.Package:
tv.errorf("implement %T %s", n, safetoken.Position(tv.pgf.Tok, n.Pos()))
// other things we knowingly ignore
case *ast.Comment, *ast.CommentGroup:
return false
default:
tv.errorf("failed to implement %T", n)
}
return true
}
func (tv *tokenVisitor) ident(id *ast.Ident) {
var obj types.Object
// emit emits a token for the identifier's extent.
emit := func(tok semtok.TokenType, modifiers ...string) {
tv.token(id.Pos(), len(id.Name), tok, modifiers)
if semDebug {
q := "nil"
if obj != nil {
q = fmt.Sprintf("%T", obj.Type()) // e.g. "*types.Map"
}
log.Printf(" use %s/%T/%s got %s %v (%s)",
id.Name, obj, q, tok, modifiers, tv.strStack())
}
}
// definition?
obj = tv.info.Defs[id]
if obj != nil {
if tok, modifiers := tv.definitionFor(id, obj); tok != "" {
emit(tok, modifiers...)
} else if semDebug {
log.Printf(" for %s/%T/%T got '' %v (%s)",
id.Name, obj, obj.Type(), modifiers, tv.strStack())
}
return
}
// use?
obj = tv.info.Uses[id]
switch obj := obj.(type) {
case *types.Builtin:
emit(semtok.TokFunction, "defaultLibrary")
case *types.Const:
if is[*types.Named](obj.Type()) &&
(id.Name == "iota" || id.Name == "true" || id.Name == "false") {
emit(semtok.TokVariable, "readonly", "defaultLibrary")
} else {
emit(semtok.TokVariable, "readonly")
}
case *types.Func:
emit(semtok.TokFunction)
case *types.Label:
// Labels are reliably covered by the syntax traversal.
case *types.Nil:
// nil is a predeclared identifier
emit(semtok.TokVariable, "readonly", "defaultLibrary")
case *types.PkgName:
emit(semtok.TokNamespace)
case *types.TypeName: // could be a TypeParam
if is[*types.TypeParam](aliases.Unalias(obj.Type())) {
emit(semtok.TokTypeParam)
} else if is[*types.Basic](obj.Type()) {
emit(semtok.TokType, "defaultLibrary")
} else {
emit(semtok.TokType)
}
case *types.Var:
if is[*types.Signature](aliases.Unalias(obj.Type())) {
emit(semtok.TokFunction)
} else if tv.isParam(obj.Pos()) {
// variable, unless use.pos is the pos of a Field in an ancestor FuncDecl
// or FuncLit and then it's a parameter
emit(semtok.TokParameter)
} else {
emit(semtok.TokVariable)
}
case nil:
if tok, modifiers := tv.unkIdent(id); tok != "" {
emit(tok, modifiers...)
}
default:
panic(obj)
}
}
// isParam reports whether the position is that of a parameter name of
// an enclosing function.
func (tv *tokenVisitor) isParam(pos token.Pos) bool {
for i := len(tv.stack) - 1; i >= 0; i-- {
switch n := tv.stack[i].(type) {
case *ast.FuncDecl:
for _, f := range n.Type.Params.List {
for _, id := range f.Names {
if id.Pos() == pos {
return true
}
}
}
case *ast.FuncLit:
for _, f := range n.Type.Params.List {
for _, id := range f.Names {
if id.Pos() == pos {
return true
}
}
}
}
}
return false
}
// unkIdent handles identifiers with no types.Object (neither use nor
// def), use the parse stack.
// A lot of these only happen when the package doesn't compile,
// but in that case it is all best-effort from the parse tree.
func (tv *tokenVisitor) unkIdent(id *ast.Ident) (semtok.TokenType, []string) {
def := []string{"definition"}
n := len(tv.stack) - 2 // parent of Ident; stack is [File ... Ident]
if n < 0 {
tv.errorf("no stack") // can't happen
return "", nil
}
switch parent := tv.stack[n].(type) {
case *ast.BinaryExpr, *ast.UnaryExpr, *ast.ParenExpr, *ast.StarExpr,
*ast.IncDecStmt, *ast.SliceExpr, *ast.ExprStmt, *ast.IndexExpr,
*ast.ReturnStmt, *ast.ChanType, *ast.SendStmt,
*ast.ForStmt, // possibly incomplete
*ast.IfStmt, /* condition */
*ast.KeyValueExpr, // either key or value
*ast.IndexListExpr:
return semtok.TokVariable, nil
case *ast.Ellipsis:
return semtok.TokType, nil
case *ast.CaseClause:
if n-2 >= 0 && is[ast.TypeSwitchStmt](tv.stack[n-2]) {
return semtok.TokType, nil
}
return semtok.TokVariable, nil
case *ast.ArrayType:
if id == parent.Len {
// or maybe a Type Param, but we can't just from the parse tree
return semtok.TokVariable, nil
} else {
return semtok.TokType, nil
}
case *ast.MapType:
return semtok.TokType, nil
case *ast.CallExpr:
if id == parent.Fun {
return semtok.TokFunction, nil
}
return semtok.TokVariable, nil
case *ast.SwitchStmt:
return semtok.TokVariable, nil
case *ast.TypeAssertExpr:
if id == parent.X {
return semtok.TokVariable, nil
} else if id == parent.Type {
return semtok.TokType, nil
}
case *ast.ValueSpec:
for _, p := range parent.Names {
if p == id {
return semtok.TokVariable, def
}
}
for _, p := range parent.Values {
if p == id {
return semtok.TokVariable, nil
}
}
return semtok.TokType, nil
case *ast.SelectorExpr: // e.ti.Selections[nd] is nil, so no help
if n-1 >= 0 {
if ce, ok := tv.stack[n-1].(*ast.CallExpr); ok {
// ... CallExpr SelectorExpr Ident (_.x())
if ce.Fun == parent && parent.Sel == id {
return semtok.TokFunction, nil
}
}
}
return semtok.TokVariable, nil
case *ast.AssignStmt:
for _, p := range parent.Lhs {
// x := ..., or x = ...
if p == id {
if parent.Tok != token.DEFINE {
def = nil
}
return semtok.TokVariable, def // '_' in _ = ...
}
}
// RHS, = x
return semtok.TokVariable, nil
case *ast.TypeSpec: // it's a type if it is either the Name or the Type
if id == parent.Type {
def = nil
}
return semtok.TokType, def
case *ast.Field:
// ident could be type in a field, or a method in an interface type, or a variable
if id == parent.Type {
return semtok.TokType, nil
}
if n > 2 &&
is[*ast.InterfaceType](tv.stack[n-2]) &&
is[*ast.FieldList](tv.stack[n-1]) {
return semtok.TokMethod, def
}
return semtok.TokVariable, nil
case *ast.LabeledStmt:
if id == parent.Label {
return semtok.TokLabel, def
}
case *ast.BranchStmt:
if id == parent.Label {
return semtok.TokLabel, nil
}
case *ast.CompositeLit:
if parent.Type == id {
return semtok.TokType, nil
}
return semtok.TokVariable, nil
case *ast.RangeStmt:
if parent.Tok != token.DEFINE {
def = nil
}
return semtok.TokVariable, def
case *ast.FuncDecl:
return semtok.TokFunction, def
default:
tv.errorf("%T unexpected: %s %s%q", parent, id.Name, tv.strStack(), tv.srcLine(id))
}
return "", nil
}
func isDeprecated(n *ast.CommentGroup) bool {
if n != nil {
for _, c := range n.List {
if strings.HasPrefix(c.Text, "// Deprecated") {
return true
}
}
}
return false
}
// definitionFor handles a defining identifier.
func (tv *tokenVisitor) definitionFor(id *ast.Ident, obj types.Object) (semtok.TokenType, []string) {
// The definition of a types.Label cannot be found by
// ascending the syntax tree, and doing so will reach the
// FuncDecl, causing us to misinterpret the label as a
// parameter (#65494).
//
// However, labels are reliably covered by the syntax
// traversal, so we don't need to use type information.
if is[*types.Label](obj) {
return "", nil
}
// PJW: look into replacing these syntactic tests with types more generally
modifiers := []string{"definition"}
for i := len(tv.stack) - 1; i >= 0; i-- {
switch ancestor := tv.stack[i].(type) {
case *ast.AssignStmt, *ast.RangeStmt:
if id.Name == "_" {
return "", nil // not really a variable
}
return semtok.TokVariable, modifiers
case *ast.GenDecl:
if isDeprecated(ancestor.Doc) {
modifiers = append(modifiers, "deprecated")
}
if ancestor.Tok == token.CONST {
modifiers = append(modifiers, "readonly")
}
return semtok.TokVariable, modifiers
case *ast.FuncDecl:
// If x is immediately under a FuncDecl, it is a function or method
if i == len(tv.stack)-2 {
if isDeprecated(ancestor.Doc) {
modifiers = append(modifiers, "deprecated")
}
if ancestor.Recv != nil {
return semtok.TokMethod, modifiers
}
return semtok.TokFunction, modifiers
}
// if x < ... < FieldList < FuncDecl, this is the receiver, a variable
// PJW: maybe not. it might be a typeparameter in the type of the receiver
if is[*ast.FieldList](tv.stack[i+1]) {
if is[*types.TypeName](obj) {
return semtok.TokTypeParam, modifiers
}
return semtok.TokVariable, nil
}
// if x < ... < FieldList < FuncType < FuncDecl, this is a param
return semtok.TokParameter, modifiers
case *ast.FuncType:
if isTypeParam(id, ancestor) {
return semtok.TokTypeParam, modifiers
}
return semtok.TokParameter, modifiers
case *ast.InterfaceType:
return semtok.TokMethod, modifiers
case *ast.TypeSpec:
// GenDecl/Typespec/FuncType/FieldList/Field/Ident
// (type A func(b uint64)) (err error)
// b and err should not be semtok.TokType, but semtok.TokVariable
// and in GenDecl/TpeSpec/StructType/FieldList/Field/Ident
// (type A struct{b uint64}
// but on type B struct{C}), C is a type, but is not being defined.
// GenDecl/TypeSpec/FieldList/Field/Ident is a typeParam
if is[*ast.FieldList](tv.stack[i+1]) {
return semtok.TokTypeParam, modifiers
}
fldm := tv.stack[len(tv.stack)-2]
if fld, ok := fldm.(*ast.Field); ok {
// if len(fld.names) == 0 this is a semtok.TokType, being used
if len(fld.Names) == 0 {
return semtok.TokType, nil
}
return semtok.TokVariable, modifiers
}
return semtok.TokType, modifiers
}
}
// can't happen
tv.errorf("failed to find the decl for %s", safetoken.Position(tv.pgf.Tok, id.Pos()))
return "", nil
}
func isTypeParam(id *ast.Ident, t *ast.FuncType) bool {
if tp := t.TypeParams; tp != nil {
for _, p := range tp.List {
for _, n := range p.Names {
if id == n {
return true
}
}
}
}
return false
}
// multiline emits a multiline token (`string` or /*comment*/).
func (tv *tokenVisitor) multiline(start, end token.Pos, tok semtok.TokenType) {
// TODO(adonovan): test with non-ASCII.
f := tv.fset.File(start)
// the hard part is finding the lengths of lines. include the \n
length := func(line int) int {
n := f.LineStart(line)
if line >= f.LineCount() {
return f.Size() - int(n)
}
return int(f.LineStart(line+1) - n)
}
spos := safetoken.StartPosition(tv.fset, start)
epos := safetoken.EndPosition(tv.fset, end)
sline := spos.Line
eline := epos.Line
// first line is from spos.Column to end
tv.token(start, length(sline)-spos.Column, tok, nil) // leng(sline)-1 - (spos.Column-1)
for i := sline + 1; i < eline; i++ {
// intermediate lines are from 1 to end
tv.token(f.LineStart(i), length(i)-1, tok, nil) // avoid the newline
}
// last line is from 1 to epos.Column
tv.token(f.LineStart(eline), epos.Column-1, tok, nil) // columns are 1-based
}
// findKeyword returns the position of a keyword by searching within
// the specified range, for when it cannot be exactly known from the AST.
// It returns NoPos if the keyword was not present in the source due to parse error.
func (tv *tokenVisitor) findKeyword(keyword string, start, end token.Pos) token.Pos {
// TODO(adonovan): use safetoken.Offset.
offset := int(start) - tv.pgf.Tok.Base()
last := int(end) - tv.pgf.Tok.Base()
buf := tv.pgf.Src
idx := bytes.Index(buf[offset:last], []byte(keyword))
if idx < 0 {
// Ill-formed code may form syntax trees without their usual tokens.
// For example, "type _ <-<-chan int" parses as <-chan (chan int),
// with two nested ChanTypes but only one chan keyword.
return token.NoPos
}
return start + token.Pos(idx)
}
func (tv *tokenVisitor) importSpec(spec *ast.ImportSpec) {
// a local package name or the last component of the Path
if spec.Name != nil {
name := spec.Name.String()
if name != "_" && name != "." {
tv.token(spec.Name.Pos(), len(name), semtok.TokNamespace, nil)
}
return // don't mark anything for . or _
}
importPath := metadata.UnquoteImportPath(spec)
if importPath == "" {
return
}
// Import strings are implementation defined. Try to match with parse information.
depID := tv.metadata.DepsByImpPath[importPath]
if depID == "" {
return
}
depMD := tv.metadataSource.Metadata(depID)
if depMD == nil {
// unexpected, but impact is that maybe some import is not colored
return
}
// Check whether the original literal contains the package's declared name.
j := strings.LastIndex(spec.Path.Value, string(depMD.Name))
if j < 0 {
// Package name does not match import path, so there is nothing to report.
return
}
// Report virtual declaration at the position of the substring.
start := spec.Path.Pos() + token.Pos(j)
tv.token(start, len(depMD.Name), semtok.TokNamespace, nil)
}
// errorf logs an error and reports a bug.
func (tv *tokenVisitor) errorf(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
bug.Report(msg)
event.Error(tv.ctx, tv.strStack(), errors.New(msg))
}
var godirectives = map[string]struct{}{
// https://pkg.go.dev/cmd/compile
"noescape": {},
"uintptrescapes": {},
"noinline": {},
"norace": {},
"nosplit": {},
"linkname": {},
// https://pkg.go.dev/go/build
"build": {},
"binary-only-package": {},
"embed": {},
}
// Tokenize godirective at the start of the comment c, if any, and the surrounding comment.
// If there is any failure, emits the entire comment as a TokComment token.
// Directives are highlighted as-is, even if used incorrectly. Typically there are
// dedicated analyzers that will warn about misuse.
func (tv *tokenVisitor) godirective(c *ast.Comment) {
// First check if '//go:directive args...' is a valid directive.
directive, args, _ := strings.Cut(c.Text, " ")
kind, _ := stringsCutPrefix(directive, "//go:")
if _, ok := godirectives[kind]; !ok {
// Unknown 'go:' directive.
tv.token(c.Pos(), len(c.Text), semtok.TokComment, nil)
return
}
// Make the 'go:directive' part stand out, the rest is comments.
tv.token(c.Pos(), len("//"), semtok.TokComment, nil)
directiveStart := c.Pos() + token.Pos(len("//"))
tv.token(directiveStart, len(directive[len("//"):]), semtok.TokNamespace, nil)
if len(args) > 0 {
tailStart := c.Pos() + token.Pos(len(directive)+len(" "))
tv.token(tailStart, len(args), semtok.TokComment, nil)
}
}
// Go 1.20 strings.CutPrefix.
func stringsCutPrefix(s, prefix string) (after string, found bool) {
if !strings.HasPrefix(s, prefix) {
return s, false
}
return s[len(prefix):], true
}
func is[T any](x any) bool {
_, ok := x.(T)
return ok
}
| tools/gopls/internal/golang/semtok.go/0 | {
"file_path": "tools/gopls/internal/golang/semtok.go",
"repo_id": "tools",
"token_count": 11935
} | 742 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package progress
import (
"context"
"fmt"
"sync"
"testing"
"golang.org/x/tools/gopls/internal/protocol"
)
type fakeClient struct {
protocol.Client
token protocol.ProgressToken
mu sync.Mutex
created, begun, reported, messages, ended int
}
func (c *fakeClient) checkToken(token protocol.ProgressToken) {
if token == nil {
panic("nil token in progress message")
}
if c.token != nil && c.token != token {
panic(fmt.Errorf("invalid token in progress message: got %v, want %v", token, c.token))
}
}
func (c *fakeClient) WorkDoneProgressCreate(ctx context.Context, params *protocol.WorkDoneProgressCreateParams) error {
c.mu.Lock()
defer c.mu.Unlock()
c.checkToken(params.Token)
c.created++
return nil
}
func (c *fakeClient) Progress(ctx context.Context, params *protocol.ProgressParams) error {
c.mu.Lock()
defer c.mu.Unlock()
c.checkToken(params.Token)
switch params.Value.(type) {
case *protocol.WorkDoneProgressBegin:
c.begun++
case *protocol.WorkDoneProgressReport:
c.reported++
case *protocol.WorkDoneProgressEnd:
c.ended++
default:
panic(fmt.Errorf("unknown progress value %T", params.Value))
}
return nil
}
func (c *fakeClient) ShowMessage(context.Context, *protocol.ShowMessageParams) error {
c.mu.Lock()
defer c.mu.Unlock()
c.messages++
return nil
}
func setup() (context.Context, *Tracker, *fakeClient) {
c := &fakeClient{}
tracker := NewTracker(c)
tracker.SetSupportsWorkDoneProgress(true)
return context.Background(), tracker, c
}
func TestProgressTracker_Reporting(t *testing.T) {
for _, test := range []struct {
name string
supported bool
token protocol.ProgressToken
wantReported, wantCreated, wantBegun, wantEnded int
wantMessages int
}{
{
name: "unsupported",
wantMessages: 2,
},
{
name: "random token",
supported: true,
wantCreated: 1,
wantBegun: 1,
wantReported: 1,
wantEnded: 1,
},
{
name: "string token",
supported: true,
token: "token",
wantBegun: 1,
wantReported: 1,
wantEnded: 1,
},
{
name: "numeric token",
supported: true,
token: 1,
wantReported: 1,
wantBegun: 1,
wantEnded: 1,
},
} {
test := test
t.Run(test.name, func(t *testing.T) {
ctx, tracker, client := setup()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
tracker.supportsWorkDoneProgress = test.supported
work := tracker.Start(ctx, "work", "message", test.token, nil)
client.mu.Lock()
gotCreated, gotBegun := client.created, client.begun
client.mu.Unlock()
if gotCreated != test.wantCreated {
t.Errorf("got %d created tokens, want %d", gotCreated, test.wantCreated)
}
if gotBegun != test.wantBegun {
t.Errorf("got %d work begun, want %d", gotBegun, test.wantBegun)
}
// Ignore errors: this is just testing the reporting behavior.
work.Report(ctx, "report", 50)
client.mu.Lock()
gotReported := client.reported
client.mu.Unlock()
if gotReported != test.wantReported {
t.Errorf("got %d progress reports, want %d", gotReported, test.wantCreated)
}
work.End(ctx, "done")
client.mu.Lock()
gotEnded, gotMessages := client.ended, client.messages
client.mu.Unlock()
if gotEnded != test.wantEnded {
t.Errorf("got %d ended reports, want %d", gotEnded, test.wantEnded)
}
if gotMessages != test.wantMessages {
t.Errorf("got %d messages, want %d", gotMessages, test.wantMessages)
}
})
}
}
func TestProgressTracker_Cancellation(t *testing.T) {
for _, token := range []protocol.ProgressToken{nil, 1, "a"} {
ctx, tracker, _ := setup()
var canceled bool
cancel := func() { canceled = true }
work := tracker.Start(ctx, "work", "message", token, cancel)
if err := tracker.Cancel(work.Token()); err != nil {
t.Fatal(err)
}
if !canceled {
t.Errorf("tracker.cancel(...): cancel not called")
}
}
}
| tools/gopls/internal/progress/progress_test.go/0 | {
"file_path": "tools/gopls/internal/progress/progress_test.go",
"repo_id": "tools",
"token_count": 1831
} | 743 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"log"
"sort"
"strings"
)
var (
// tsclient.go has 3 sections
cdecls = make(sortedMap[string])
ccases = make(sortedMap[string])
cfuncs = make(sortedMap[string])
// tsserver.go has 3 sections
sdecls = make(sortedMap[string])
scases = make(sortedMap[string])
sfuncs = make(sortedMap[string])
// tsprotocol.go has 2 sections
types = make(sortedMap[string])
consts = make(sortedMap[string])
// tsjson has 1 section
jsons = make(sortedMap[string])
)
func generateOutput(model *Model) {
for _, r := range model.Requests {
genDecl(model, r.Method, r.Params, r.Result, r.Direction)
genCase(model, r.Method, r.Params, r.Result, r.Direction)
genFunc(model, r.Method, r.Params, r.Result, r.Direction, false)
}
for _, n := range model.Notifications {
if n.Method == "$/cancelRequest" {
continue // handled internally by jsonrpc2
}
genDecl(model, n.Method, n.Params, nil, n.Direction)
genCase(model, n.Method, n.Params, nil, n.Direction)
genFunc(model, n.Method, n.Params, nil, n.Direction, true)
}
genStructs(model)
genAliases(model)
genGenTypes() // generate the unnamed types
genConsts(model)
genMarshal()
}
func genDecl(model *Model, method string, param, result *Type, dir string) {
fname := methodName(method)
p := ""
if notNil(param) {
p = ", *" + goplsName(param)
}
ret := "error"
if notNil(result) {
tp := goplsName(result)
if !hasNilValue(tp) {
tp = "*" + tp
}
ret = fmt.Sprintf("(%s, error)", tp)
}
// special gopls compatibility case (PJW: still needed?)
switch method {
case "workspace/configuration":
// was And_Param_workspace_configuration, but the type substitution doesn't work,
// as ParamConfiguration is embedded in And_Param_workspace_configuration
p = ", *ParamConfiguration"
ret = "([]LSPAny, error)"
}
fragment := strings.ReplaceAll(strings.TrimPrefix(method, "$/"), "/", "_")
msg := fmt.Sprintf("\t%s\t%s(context.Context%s) %s\n", lspLink(model, fragment), fname, p, ret)
switch dir {
case "clientToServer":
sdecls[method] = msg
case "serverToClient":
cdecls[method] = msg
case "both":
sdecls[method] = msg
cdecls[method] = msg
default:
log.Fatalf("impossible direction %q", dir)
}
}
func genCase(model *Model, method string, param, result *Type, dir string) {
out := new(bytes.Buffer)
fmt.Fprintf(out, "\tcase %q:\n", method)
var p string
fname := methodName(method)
if notNil(param) {
nm := goplsName(param)
if method == "workspace/configuration" { // gopls compatibility
// was And_Param_workspace_configuration, which contains ParamConfiguration
// so renaming the type leads to circular definitions
nm = "ParamConfiguration" // gopls compatibility
}
fmt.Fprintf(out, "\t\tvar params %s\n", nm)
fmt.Fprintf(out, "\t\tif err := UnmarshalJSON(r.Params(), ¶ms); err != nil {\n")
fmt.Fprintf(out, "\t\t\treturn true, sendParseError(ctx, reply, err)\n\t\t}\n")
p = ", ¶ms"
}
if notNil(result) {
fmt.Fprintf(out, "\t\tresp, err := %%s.%s(ctx%s)\n", fname, p)
out.WriteString("\t\tif err != nil {\n")
out.WriteString("\t\t\treturn true, reply(ctx, nil, err)\n")
out.WriteString("\t\t}\n")
out.WriteString("\t\treturn true, reply(ctx, resp, nil)\n")
} else {
fmt.Fprintf(out, "\t\terr := %%s.%s(ctx%s)\n", fname, p)
out.WriteString("\t\treturn true, reply(ctx, nil, err)\n")
}
out.WriteString("\n")
msg := out.String()
switch dir {
case "clientToServer":
scases[method] = fmt.Sprintf(msg, "server")
case "serverToClient":
ccases[method] = fmt.Sprintf(msg, "client")
case "both":
scases[method] = fmt.Sprintf(msg, "server")
ccases[method] = fmt.Sprintf(msg, "client")
default:
log.Fatalf("impossible direction %q", dir)
}
}
func genFunc(model *Model, method string, param, result *Type, dir string, isnotify bool) {
out := new(bytes.Buffer)
var p, r string
var goResult string
if notNil(param) {
p = ", params *" + goplsName(param)
}
if notNil(result) {
goResult = goplsName(result)
if !hasNilValue(goResult) {
goResult = "*" + goResult
}
r = fmt.Sprintf("(%s, error)", goResult)
} else {
r = "error"
}
// special gopls compatibility case
switch method {
case "workspace/configuration":
// was And_Param_workspace_configuration, but the type substitution doesn't work,
// as ParamConfiguration is embedded in And_Param_workspace_configuration
p = ", params *ParamConfiguration"
r = "([]LSPAny, error)"
goResult = "[]LSPAny"
}
fname := methodName(method)
fmt.Fprintf(out, "func (s *%%sDispatcher) %s(ctx context.Context%s) %s {\n",
fname, p, r)
if !notNil(result) {
if isnotify {
if notNil(param) {
fmt.Fprintf(out, "\treturn s.sender.Notify(ctx, %q, params)\n", method)
} else {
fmt.Fprintf(out, "\treturn s.sender.Notify(ctx, %q, nil)\n", method)
}
} else {
if notNil(param) {
fmt.Fprintf(out, "\treturn s.sender.Call(ctx, %q, params, nil)\n", method)
} else {
fmt.Fprintf(out, "\treturn s.sender.Call(ctx, %q, nil, nil)\n", method)
}
}
} else {
fmt.Fprintf(out, "\tvar result %s\n", goResult)
if isnotify {
if notNil(param) {
fmt.Fprintf(out, "\ts.sender.Notify(ctx, %q, params)\n", method)
} else {
fmt.Fprintf(out, "\t\tif err := s.sender.Notify(ctx, %q, nil); err != nil {\n", method)
}
} else {
if notNil(param) {
fmt.Fprintf(out, "\t\tif err := s.sender.Call(ctx, %q, params, &result); err != nil {\n", method)
} else {
fmt.Fprintf(out, "\t\tif err := s.sender.Call(ctx, %q, nil, &result); err != nil {\n", method)
}
}
fmt.Fprintf(out, "\t\treturn nil, err\n\t}\n\treturn result, nil\n")
}
out.WriteString("}\n")
msg := out.String()
switch dir {
case "clientToServer":
sfuncs[method] = fmt.Sprintf(msg, "server")
case "serverToClient":
cfuncs[method] = fmt.Sprintf(msg, "client")
case "both":
sfuncs[method] = fmt.Sprintf(msg, "server")
cfuncs[method] = fmt.Sprintf(msg, "client")
default:
log.Fatalf("impossible direction %q", dir)
}
}
func genStructs(model *Model) {
structures := make(map[string]*Structure) // for expanding Extends
for _, s := range model.Structures {
structures[s.Name] = s
}
for _, s := range model.Structures {
out := new(bytes.Buffer)
generateDoc(out, s.Documentation)
nm := goName(s.Name)
if nm == "string" { // an unacceptable strut name
// a weird case, and needed only so the generated code contains the old gopls code
nm = "DocumentDiagnosticParams"
}
fmt.Fprintf(out, "//\n")
out.WriteString(lspLink(model, camelCase(s.Name)))
fmt.Fprintf(out, "type %s struct {%s\n", nm, linex(s.Line))
// for gpls compatibilitye, embed most extensions, but expand the rest some day
props := append([]NameType{}, s.Properties...)
if s.Name == "SymbolInformation" { // but expand this one
for _, ex := range s.Extends {
fmt.Fprintf(out, "\t// extends %s\n", ex.Name)
props = append(props, structures[ex.Name].Properties...)
}
genProps(out, props, nm)
} else {
genProps(out, props, nm)
for _, ex := range s.Extends {
fmt.Fprintf(out, "\t%s\n", goName(ex.Name))
}
}
for _, ex := range s.Mixins {
fmt.Fprintf(out, "\t%s\n", goName(ex.Name))
}
out.WriteString("}\n")
types[nm] = out.String()
}
// base types
// (For URI and DocumentURI, see ../uri.go.)
types["LSPAny"] = "type LSPAny = interface{}\n"
// A special case, the only previously existing Or type
types["DocumentDiagnosticReport"] = "type DocumentDiagnosticReport = Or_DocumentDiagnosticReport // (alias) \n"
}
// "FooBar" -> "fooBar"
func camelCase(TitleCased string) string {
return strings.ToLower(TitleCased[:1]) + TitleCased[1:]
}
func lspLink(model *Model, fragment string) string {
// Derive URL version from metaData.version in JSON file.
parts := strings.Split(model.Version.Version, ".") // e.g. "3.17.0"
return fmt.Sprintf("// See https://microsoft.github.io/language-server-protocol/specifications/lsp/%s.%s/specification#%s\n",
parts[0], parts[1], // major.minor
fragment)
}
func genProps(out *bytes.Buffer, props []NameType, name string) {
for _, p := range props {
tp := goplsName(p.Type)
if newNm, ok := renameProp[prop{name, p.Name}]; ok {
usedRenameProp[prop{name, p.Name}] = true
if tp == newNm {
log.Printf("renameProp useless {%q, %q} for %s", name, p.Name, tp)
}
tp = newNm
}
// it's a pointer if it is optional, or for gopls compatibility
opt, star := propStar(name, p, tp)
json := fmt.Sprintf(" `json:\"%s%s\"`", p.Name, opt)
generateDoc(out, p.Documentation)
fmt.Fprintf(out, "\t%s %s%s %s\n", goName(p.Name), star, tp, json)
}
}
func genAliases(model *Model) {
for _, ta := range model.TypeAliases {
out := new(bytes.Buffer)
generateDoc(out, ta.Documentation)
nm := goName(ta.Name)
if nm != ta.Name {
continue // renamed the type, e.g., "DocumentDiagnosticReport", an or-type to "string"
}
tp := goplsName(ta.Type)
fmt.Fprintf(out, "//\n")
out.WriteString(lspLink(model, camelCase(ta.Name)))
fmt.Fprintf(out, "type %s = %s // (alias)\n", nm, tp)
types[nm] = out.String()
}
}
func genGenTypes() {
for _, nt := range genTypes {
out := new(bytes.Buffer)
nm := goplsName(nt.typ)
switch nt.kind {
case "literal":
fmt.Fprintf(out, "// created for Literal (%s)\n", nt.name)
fmt.Fprintf(out, "type %s struct {%s\n", nm, linex(nt.line+1))
genProps(out, nt.properties, nt.name) // systematic name, not gopls name; is this a good choice?
case "or":
if !strings.HasPrefix(nm, "Or") {
// It was replaced by a narrower type defined elsewhere
continue
}
names := []string{}
for _, t := range nt.items {
if notNil(t) {
names = append(names, goplsName(t))
}
}
sort.Strings(names)
fmt.Fprintf(out, "// created for Or %v\n", names)
fmt.Fprintf(out, "type %s struct {%s\n", nm, linex(nt.line+1))
fmt.Fprintf(out, "\tValue interface{} `json:\"value\"`\n")
case "and":
fmt.Fprintf(out, "// created for And\n")
fmt.Fprintf(out, "type %s struct {%s\n", nm, linex(nt.line+1))
for _, x := range nt.items {
nm := goplsName(x)
fmt.Fprintf(out, "\t%s\n", nm)
}
case "tuple": // there's only this one
nt.name = "UIntCommaUInt"
fmt.Fprintf(out, "//created for Tuple\ntype %s struct {%s\n", nm, linex(nt.line+1))
fmt.Fprintf(out, "\tFld0 uint32 `json:\"fld0\"`\n")
fmt.Fprintf(out, "\tFld1 uint32 `json:\"fld1\"`\n")
default:
log.Fatalf("%s not handled", nt.kind)
}
out.WriteString("}\n")
types[nm] = out.String()
}
}
func genConsts(model *Model) {
for _, e := range model.Enumerations {
out := new(bytes.Buffer)
generateDoc(out, e.Documentation)
tp := goplsName(e.Type)
nm := goName(e.Name)
fmt.Fprintf(out, "type %s %s%s\n", nm, tp, linex(e.Line))
types[nm] = out.String()
vals := new(bytes.Buffer)
generateDoc(vals, e.Documentation)
for _, v := range e.Values {
generateDoc(vals, v.Documentation)
nm := goName(v.Name)
more, ok := disambiguate[e.Name]
if ok {
usedDisambiguate[e.Name] = true
nm = more.prefix + nm + more.suffix
nm = goName(nm) // stringType
}
var val string
switch v := v.Value.(type) {
case string:
val = fmt.Sprintf("%q", v)
case float64:
val = fmt.Sprintf("%d", int(v))
default:
log.Fatalf("impossible type %T", v)
}
fmt.Fprintf(vals, "\t%s %s = %s%s\n", nm, e.Name, val, linex(v.Line))
}
consts[nm] = vals.String()
}
}
func genMarshal() {
for _, nt := range genTypes {
nm := goplsName(nt.typ)
if !strings.HasPrefix(nm, "Or") {
continue
}
names := []string{}
for _, t := range nt.items {
if notNil(t) {
names = append(names, goplsName(t))
}
}
sort.Strings(names)
var buf bytes.Buffer
fmt.Fprintf(&buf, "func (t %s) MarshalJSON() ([]byte, error) {\n", nm)
buf.WriteString("\tswitch x := t.Value.(type){\n")
for _, nmx := range names {
fmt.Fprintf(&buf, "\tcase %s:\n", nmx)
fmt.Fprintf(&buf, "\t\treturn json.Marshal(x)\n")
}
buf.WriteString("\tcase nil:\n\t\treturn []byte(\"null\"), nil\n\t}\n")
fmt.Fprintf(&buf, "\treturn nil, fmt.Errorf(\"type %%T not one of %v\", t)\n", names)
buf.WriteString("}\n\n")
fmt.Fprintf(&buf, "func (t *%s) UnmarshalJSON(x []byte) error {\n", nm)
buf.WriteString("\tif string(x) == \"null\" {\n\t\tt.Value = nil\n\t\t\treturn nil\n\t}\n")
for i, nmx := range names {
fmt.Fprintf(&buf, "\tvar h%d %s\n", i, nmx)
fmt.Fprintf(&buf, "\tif err := json.Unmarshal(x, &h%d); err == nil {\n\t\tt.Value = h%d\n\t\t\treturn nil\n\t\t}\n", i, i)
}
fmt.Fprintf(&buf, "return &UnmarshalError{\"unmarshal failed to match one of %v\"}", names)
buf.WriteString("}\n\n")
jsons[nm] = buf.String()
}
}
func linex(n int) string {
if *lineNumbers {
return fmt.Sprintf(" // line %d", n)
}
return ""
}
func goplsName(t *Type) string {
nm := typeNames[t]
// translate systematic name to gopls name
if newNm, ok := goplsType[nm]; ok {
usedGoplsType[nm] = true
nm = newNm
}
return nm
}
func notNil(t *Type) bool { // shutdwon is the special case that needs this
return t != nil && (t.Kind != "base" || t.Name != "null")
}
func hasNilValue(t string) bool {
// this may be unreliable, and need a supplementary table
if strings.HasPrefix(t, "[]") || strings.HasPrefix(t, "*") {
return true
}
if t == "interface{}" || t == "any" {
return true
}
// that's all the cases that occur currently
return false
}
| tools/gopls/internal/protocol/generate/output.go/0 | {
"file_path": "tools/gopls/internal/protocol/generate/output.go",
"repo_id": "tools",
"token_count": 5798
} | 744 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated for LSP. DO NOT EDIT.
package protocol
// Code generated from protocol/metaModel.json at ref release/protocol/3.17.6-next.2 (hash 654dc9be6673c61476c28fda604406279c3258d7).
// https://github.com/microsoft/vscode-languageserver-node/blob/release/protocol/3.17.6-next.2/protocol/metaModel.json
// LSP metaData.version = 3.17.0.
import "encoding/json"
import "fmt"
// UnmarshalError indicates that a JSON value did not conform to
// one of the expected cases of an LSP union type.
type UnmarshalError struct {
msg string
}
func (e UnmarshalError) Error() string {
return e.msg
}
func (t OrPLocation_workspace_symbol) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case Location:
return json.Marshal(x)
case LocationUriOnly:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [Location LocationUriOnly]", t)
}
func (t *OrPLocation_workspace_symbol) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 Location
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 LocationUriOnly
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [Location LocationUriOnly]"}
}
func (t OrPSection_workspace_didChangeConfiguration) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case []string:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [[]string string]", t)
}
func (t *OrPSection_workspace_didChangeConfiguration) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 []string
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [[]string string]"}
}
func (t OrPTooltipPLabel) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MarkupContent:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MarkupContent string]", t)
}
func (t *OrPTooltipPLabel) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MarkupContent
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MarkupContent string]"}
}
func (t OrPTooltip_textDocument_inlayHint) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MarkupContent:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MarkupContent string]", t)
}
func (t *OrPTooltip_textDocument_inlayHint) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MarkupContent
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MarkupContent string]"}
}
func (t Or_CancelParams_id) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case int32:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [int32 string]", t)
}
func (t *Or_CancelParams_id) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 int32
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [int32 string]"}
}
func (t Or_ClientSemanticTokensRequestOptions_full) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case ClientSemanticTokensRequestFullDelta:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [ClientSemanticTokensRequestFullDelta bool]", t)
}
func (t *Or_ClientSemanticTokensRequestOptions_full) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 ClientSemanticTokensRequestFullDelta
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [ClientSemanticTokensRequestFullDelta bool]"}
}
func (t Or_ClientSemanticTokensRequestOptions_range) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case Lit_ClientSemanticTokensRequestOptions_range_Item1:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]", t)
}
func (t *Or_ClientSemanticTokensRequestOptions_range) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 Lit_ClientSemanticTokensRequestOptions_range_Item1
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [Lit_ClientSemanticTokensRequestOptions_range_Item1 bool]"}
}
func (t Or_CompletionItemDefaults_editRange) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case EditRangeWithInsertReplace:
return json.Marshal(x)
case Range:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [EditRangeWithInsertReplace Range]", t)
}
func (t *Or_CompletionItemDefaults_editRange) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 EditRangeWithInsertReplace
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 Range
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [EditRangeWithInsertReplace Range]"}
}
func (t Or_CompletionItem_documentation) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MarkupContent:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MarkupContent string]", t)
}
func (t *Or_CompletionItem_documentation) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MarkupContent
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MarkupContent string]"}
}
func (t Or_CompletionItem_textEdit) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case InsertReplaceEdit:
return json.Marshal(x)
case TextEdit:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [InsertReplaceEdit TextEdit]", t)
}
func (t *Or_CompletionItem_textEdit) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 InsertReplaceEdit
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TextEdit
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [InsertReplaceEdit TextEdit]"}
}
func (t Or_Definition) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case Location:
return json.Marshal(x)
case []Location:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [Location []Location]", t)
}
func (t *Or_Definition) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 Location
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 []Location
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [Location []Location]"}
}
func (t Or_Diagnostic_code) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case int32:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [int32 string]", t)
}
func (t *Or_Diagnostic_code) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 int32
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [int32 string]"}
}
func (t Or_DocumentDiagnosticReport) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case RelatedFullDocumentDiagnosticReport:
return json.Marshal(x)
case RelatedUnchangedDocumentDiagnosticReport:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]", t)
}
func (t *Or_DocumentDiagnosticReport) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 RelatedFullDocumentDiagnosticReport
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 RelatedUnchangedDocumentDiagnosticReport
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [RelatedFullDocumentDiagnosticReport RelatedUnchangedDocumentDiagnosticReport]"}
}
func (t Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case FullDocumentDiagnosticReport:
return json.Marshal(x)
case UnchangedDocumentDiagnosticReport:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]", t)
}
func (t *Or_DocumentDiagnosticReportPartialResult_relatedDocuments_Value) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 FullDocumentDiagnosticReport
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 UnchangedDocumentDiagnosticReport
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]"}
}
func (t Or_DocumentFilter) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookCellTextDocumentFilter:
return json.Marshal(x)
case TextDocumentFilter:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookCellTextDocumentFilter TextDocumentFilter]", t)
}
func (t *Or_DocumentFilter) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookCellTextDocumentFilter
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TextDocumentFilter
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookCellTextDocumentFilter TextDocumentFilter]"}
}
func (t Or_GlobPattern) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case Pattern:
return json.Marshal(x)
case RelativePattern:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [Pattern RelativePattern]", t)
}
func (t *Or_GlobPattern) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 Pattern
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 RelativePattern
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [Pattern RelativePattern]"}
}
func (t Or_Hover_contents) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MarkedString:
return json.Marshal(x)
case MarkupContent:
return json.Marshal(x)
case []MarkedString:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MarkedString MarkupContent []MarkedString]", t)
}
func (t *Or_Hover_contents) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MarkedString
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 MarkupContent
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 []MarkedString
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MarkedString MarkupContent []MarkedString]"}
}
func (t Or_InlayHint_label) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case []InlayHintLabelPart:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [[]InlayHintLabelPart string]", t)
}
func (t *Or_InlayHint_label) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 []InlayHintLabelPart
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [[]InlayHintLabelPart string]"}
}
func (t Or_InlineCompletionItem_insertText) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case StringValue:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [StringValue string]", t)
}
func (t *Or_InlineCompletionItem_insertText) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 StringValue
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [StringValue string]"}
}
func (t Or_InlineValue) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case InlineValueEvaluatableExpression:
return json.Marshal(x)
case InlineValueText:
return json.Marshal(x)
case InlineValueVariableLookup:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]", t)
}
func (t *Or_InlineValue) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 InlineValueEvaluatableExpression
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 InlineValueText
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 InlineValueVariableLookup
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [InlineValueEvaluatableExpression InlineValueText InlineValueVariableLookup]"}
}
func (t Or_MarkedString) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MarkedStringWithLanguage:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MarkedStringWithLanguage string]", t)
}
func (t *Or_MarkedString) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MarkedStringWithLanguage
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MarkedStringWithLanguage string]"}
}
func (t Or_NotebookCellTextDocumentFilter_notebook) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookDocumentFilter:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookDocumentFilter string]", t)
}
func (t *Or_NotebookCellTextDocumentFilter_notebook) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookDocumentFilter
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookDocumentFilter string]"}
}
func (t Or_NotebookDocumentFilter) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookDocumentFilterNotebookType:
return json.Marshal(x)
case NotebookDocumentFilterPattern:
return json.Marshal(x)
case NotebookDocumentFilterScheme:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]", t)
}
func (t *Or_NotebookDocumentFilter) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookDocumentFilterNotebookType
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 NotebookDocumentFilterPattern
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 NotebookDocumentFilterScheme
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookDocumentFilterNotebookType NotebookDocumentFilterPattern NotebookDocumentFilterScheme]"}
}
func (t Or_NotebookDocumentFilterWithCells_notebook) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookDocumentFilter:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookDocumentFilter string]", t)
}
func (t *Or_NotebookDocumentFilterWithCells_notebook) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookDocumentFilter
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookDocumentFilter string]"}
}
func (t Or_NotebookDocumentFilterWithNotebook_notebook) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookDocumentFilter:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookDocumentFilter string]", t)
}
func (t *Or_NotebookDocumentFilterWithNotebook_notebook) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookDocumentFilter
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookDocumentFilter string]"}
}
func (t Or_NotebookDocumentSyncOptions_notebookSelector_Elem) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookDocumentFilterWithCells:
return json.Marshal(x)
case NotebookDocumentFilterWithNotebook:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]", t)
}
func (t *Or_NotebookDocumentSyncOptions_notebookSelector_Elem) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookDocumentFilterWithCells
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 NotebookDocumentFilterWithNotebook
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookDocumentFilterWithCells NotebookDocumentFilterWithNotebook]"}
}
func (t Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case FullDocumentDiagnosticReport:
return json.Marshal(x)
case UnchangedDocumentDiagnosticReport:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]", t)
}
func (t *Or_RelatedFullDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 FullDocumentDiagnosticReport
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 UnchangedDocumentDiagnosticReport
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]"}
}
func (t Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case FullDocumentDiagnosticReport:
return json.Marshal(x)
case UnchangedDocumentDiagnosticReport:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]", t)
}
func (t *Or_RelatedUnchangedDocumentDiagnosticReport_relatedDocuments_Value) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 FullDocumentDiagnosticReport
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 UnchangedDocumentDiagnosticReport
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [FullDocumentDiagnosticReport UnchangedDocumentDiagnosticReport]"}
}
func (t Or_Result_textDocument_codeAction_Item0_Elem) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case CodeAction:
return json.Marshal(x)
case Command:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [CodeAction Command]", t)
}
func (t *Or_Result_textDocument_codeAction_Item0_Elem) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 CodeAction
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 Command
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [CodeAction Command]"}
}
func (t Or_Result_textDocument_inlineCompletion) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case InlineCompletionList:
return json.Marshal(x)
case []InlineCompletionItem:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [InlineCompletionList []InlineCompletionItem]", t)
}
func (t *Or_Result_textDocument_inlineCompletion) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 InlineCompletionList
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 []InlineCompletionItem
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [InlineCompletionList []InlineCompletionItem]"}
}
func (t Or_SemanticTokensOptions_full) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case SemanticTokensFullDelta:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [SemanticTokensFullDelta bool]", t)
}
func (t *Or_SemanticTokensOptions_full) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 SemanticTokensFullDelta
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [SemanticTokensFullDelta bool]"}
}
func (t Or_SemanticTokensOptions_range) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case PRangeESemanticTokensOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [PRangeESemanticTokensOptions bool]", t)
}
func (t *Or_SemanticTokensOptions_range) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 PRangeESemanticTokensOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [PRangeESemanticTokensOptions bool]"}
}
func (t Or_ServerCapabilities_callHierarchyProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case CallHierarchyOptions:
return json.Marshal(x)
case CallHierarchyRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_callHierarchyProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 CallHierarchyOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 CallHierarchyRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [CallHierarchyOptions CallHierarchyRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_codeActionProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case CodeActionOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [CodeActionOptions bool]", t)
}
func (t *Or_ServerCapabilities_codeActionProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 CodeActionOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [CodeActionOptions bool]"}
}
func (t Or_ServerCapabilities_colorProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DocumentColorOptions:
return json.Marshal(x)
case DocumentColorRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DocumentColorOptions DocumentColorRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_colorProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DocumentColorOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 DocumentColorRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DocumentColorOptions DocumentColorRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_declarationProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DeclarationOptions:
return json.Marshal(x)
case DeclarationRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DeclarationOptions DeclarationRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_declarationProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DeclarationOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 DeclarationRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DeclarationOptions DeclarationRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_definitionProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DefinitionOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DefinitionOptions bool]", t)
}
func (t *Or_ServerCapabilities_definitionProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DefinitionOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DefinitionOptions bool]"}
}
func (t Or_ServerCapabilities_diagnosticProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DiagnosticOptions:
return json.Marshal(x)
case DiagnosticRegistrationOptions:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DiagnosticOptions DiagnosticRegistrationOptions]", t)
}
func (t *Or_ServerCapabilities_diagnosticProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DiagnosticOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 DiagnosticRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DiagnosticOptions DiagnosticRegistrationOptions]"}
}
func (t Or_ServerCapabilities_documentFormattingProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DocumentFormattingOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DocumentFormattingOptions bool]", t)
}
func (t *Or_ServerCapabilities_documentFormattingProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DocumentFormattingOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DocumentFormattingOptions bool]"}
}
func (t Or_ServerCapabilities_documentHighlightProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DocumentHighlightOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DocumentHighlightOptions bool]", t)
}
func (t *Or_ServerCapabilities_documentHighlightProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DocumentHighlightOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DocumentHighlightOptions bool]"}
}
func (t Or_ServerCapabilities_documentRangeFormattingProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DocumentRangeFormattingOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DocumentRangeFormattingOptions bool]", t)
}
func (t *Or_ServerCapabilities_documentRangeFormattingProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DocumentRangeFormattingOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DocumentRangeFormattingOptions bool]"}
}
func (t Or_ServerCapabilities_documentSymbolProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case DocumentSymbolOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [DocumentSymbolOptions bool]", t)
}
func (t *Or_ServerCapabilities_documentSymbolProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 DocumentSymbolOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [DocumentSymbolOptions bool]"}
}
func (t Or_ServerCapabilities_foldingRangeProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case FoldingRangeOptions:
return json.Marshal(x)
case FoldingRangeRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_foldingRangeProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 FoldingRangeOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 FoldingRangeRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [FoldingRangeOptions FoldingRangeRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_hoverProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case HoverOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [HoverOptions bool]", t)
}
func (t *Or_ServerCapabilities_hoverProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 HoverOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [HoverOptions bool]"}
}
func (t Or_ServerCapabilities_implementationProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case ImplementationOptions:
return json.Marshal(x)
case ImplementationRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [ImplementationOptions ImplementationRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_implementationProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 ImplementationOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 ImplementationRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [ImplementationOptions ImplementationRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_inlayHintProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case InlayHintOptions:
return json.Marshal(x)
case InlayHintRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [InlayHintOptions InlayHintRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_inlayHintProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 InlayHintOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 InlayHintRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [InlayHintOptions InlayHintRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_inlineCompletionProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case InlineCompletionOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [InlineCompletionOptions bool]", t)
}
func (t *Or_ServerCapabilities_inlineCompletionProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 InlineCompletionOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [InlineCompletionOptions bool]"}
}
func (t Or_ServerCapabilities_inlineValueProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case InlineValueOptions:
return json.Marshal(x)
case InlineValueRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [InlineValueOptions InlineValueRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_inlineValueProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 InlineValueOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 InlineValueRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [InlineValueOptions InlineValueRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_linkedEditingRangeProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case LinkedEditingRangeOptions:
return json.Marshal(x)
case LinkedEditingRangeRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_linkedEditingRangeProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 LinkedEditingRangeOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 LinkedEditingRangeRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [LinkedEditingRangeOptions LinkedEditingRangeRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_monikerProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MonikerOptions:
return json.Marshal(x)
case MonikerRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MonikerOptions MonikerRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_monikerProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MonikerOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 MonikerRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MonikerOptions MonikerRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_notebookDocumentSync) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case NotebookDocumentSyncOptions:
return json.Marshal(x)
case NotebookDocumentSyncRegistrationOptions:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]", t)
}
func (t *Or_ServerCapabilities_notebookDocumentSync) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 NotebookDocumentSyncOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 NotebookDocumentSyncRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [NotebookDocumentSyncOptions NotebookDocumentSyncRegistrationOptions]"}
}
func (t Or_ServerCapabilities_referencesProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case ReferenceOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [ReferenceOptions bool]", t)
}
func (t *Or_ServerCapabilities_referencesProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 ReferenceOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [ReferenceOptions bool]"}
}
func (t Or_ServerCapabilities_renameProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case RenameOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [RenameOptions bool]", t)
}
func (t *Or_ServerCapabilities_renameProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 RenameOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [RenameOptions bool]"}
}
func (t Or_ServerCapabilities_selectionRangeProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case SelectionRangeOptions:
return json.Marshal(x)
case SelectionRangeRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_selectionRangeProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 SelectionRangeOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 SelectionRangeRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [SelectionRangeOptions SelectionRangeRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_semanticTokensProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case SemanticTokensOptions:
return json.Marshal(x)
case SemanticTokensRegistrationOptions:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [SemanticTokensOptions SemanticTokensRegistrationOptions]", t)
}
func (t *Or_ServerCapabilities_semanticTokensProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 SemanticTokensOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 SemanticTokensRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [SemanticTokensOptions SemanticTokensRegistrationOptions]"}
}
func (t Or_ServerCapabilities_textDocumentSync) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case TextDocumentSyncKind:
return json.Marshal(x)
case TextDocumentSyncOptions:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [TextDocumentSyncKind TextDocumentSyncOptions]", t)
}
func (t *Or_ServerCapabilities_textDocumentSync) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 TextDocumentSyncKind
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TextDocumentSyncOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [TextDocumentSyncKind TextDocumentSyncOptions]"}
}
func (t Or_ServerCapabilities_typeDefinitionProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case TypeDefinitionOptions:
return json.Marshal(x)
case TypeDefinitionRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_typeDefinitionProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 TypeDefinitionOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TypeDefinitionRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [TypeDefinitionOptions TypeDefinitionRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_typeHierarchyProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case TypeHierarchyOptions:
return json.Marshal(x)
case TypeHierarchyRegistrationOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]", t)
}
func (t *Or_ServerCapabilities_typeHierarchyProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 TypeHierarchyOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TypeHierarchyRegistrationOptions
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 bool
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [TypeHierarchyOptions TypeHierarchyRegistrationOptions bool]"}
}
func (t Or_ServerCapabilities_workspaceSymbolProvider) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case WorkspaceSymbolOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [WorkspaceSymbolOptions bool]", t)
}
func (t *Or_ServerCapabilities_workspaceSymbolProvider) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 WorkspaceSymbolOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [WorkspaceSymbolOptions bool]"}
}
func (t Or_SignatureInformation_documentation) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case MarkupContent:
return json.Marshal(x)
case string:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [MarkupContent string]", t)
}
func (t *Or_SignatureInformation_documentation) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 MarkupContent
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 string
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [MarkupContent string]"}
}
func (t Or_TextDocumentEdit_edits_Elem) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case AnnotatedTextEdit:
return json.Marshal(x)
case TextEdit:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [AnnotatedTextEdit TextEdit]", t)
}
func (t *Or_TextDocumentEdit_edits_Elem) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 AnnotatedTextEdit
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TextEdit
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [AnnotatedTextEdit TextEdit]"}
}
func (t Or_TextDocumentFilter) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case TextDocumentFilterLanguage:
return json.Marshal(x)
case TextDocumentFilterPattern:
return json.Marshal(x)
case TextDocumentFilterScheme:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]", t)
}
func (t *Or_TextDocumentFilter) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 TextDocumentFilterLanguage
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 TextDocumentFilterPattern
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 TextDocumentFilterScheme
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [TextDocumentFilterLanguage TextDocumentFilterPattern TextDocumentFilterScheme]"}
}
func (t Or_TextDocumentSyncOptions_save) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case SaveOptions:
return json.Marshal(x)
case bool:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [SaveOptions bool]", t)
}
func (t *Or_TextDocumentSyncOptions_save) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 SaveOptions
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 bool
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [SaveOptions bool]"}
}
func (t Or_WorkspaceDocumentDiagnosticReport) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case WorkspaceFullDocumentDiagnosticReport:
return json.Marshal(x)
case WorkspaceUnchangedDocumentDiagnosticReport:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]", t)
}
func (t *Or_WorkspaceDocumentDiagnosticReport) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 WorkspaceFullDocumentDiagnosticReport
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 WorkspaceUnchangedDocumentDiagnosticReport
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [WorkspaceFullDocumentDiagnosticReport WorkspaceUnchangedDocumentDiagnosticReport]"}
}
func (t Or_WorkspaceEdit_documentChanges_Elem) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case CreateFile:
return json.Marshal(x)
case DeleteFile:
return json.Marshal(x)
case RenameFile:
return json.Marshal(x)
case TextDocumentEdit:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [CreateFile DeleteFile RenameFile TextDocumentEdit]", t)
}
func (t *Or_WorkspaceEdit_documentChanges_Elem) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 CreateFile
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 DeleteFile
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
var h2 RenameFile
if err := json.Unmarshal(x, &h2); err == nil {
t.Value = h2
return nil
}
var h3 TextDocumentEdit
if err := json.Unmarshal(x, &h3); err == nil {
t.Value = h3
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [CreateFile DeleteFile RenameFile TextDocumentEdit]"}
}
func (t Or_textDocument_declaration) MarshalJSON() ([]byte, error) {
switch x := t.Value.(type) {
case Declaration:
return json.Marshal(x)
case []DeclarationLink:
return json.Marshal(x)
case nil:
return []byte("null"), nil
}
return nil, fmt.Errorf("type %T not one of [Declaration []DeclarationLink]", t)
}
func (t *Or_textDocument_declaration) UnmarshalJSON(x []byte) error {
if string(x) == "null" {
t.Value = nil
return nil
}
var h0 Declaration
if err := json.Unmarshal(x, &h0); err == nil {
t.Value = h0
return nil
}
var h1 []DeclarationLink
if err := json.Unmarshal(x, &h1); err == nil {
t.Value = h1
return nil
}
return &UnmarshalError{"unmarshal failed to match one of [Declaration []DeclarationLink]"}
}
| tools/gopls/internal/protocol/tsjson.go/0 | {
"file_path": "tools/gopls/internal/protocol/tsjson.go",
"repo_id": "tools",
"token_count": 21618
} | 745 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package server
import (
"context"
"fmt"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/golang"
"golang.org/x/tools/gopls/internal/label"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/telemetry"
"golang.org/x/tools/gopls/internal/template"
"golang.org/x/tools/internal/event"
)
func (s *server) Definition(ctx context.Context, params *protocol.DefinitionParams) (_ []protocol.Location, rerr error) {
recordLatency := telemetry.StartLatencyTimer("definition")
defer func() {
recordLatency(ctx, rerr)
}()
ctx, done := event.Start(ctx, "lsp.Server.definition", label.URI.Of(params.TextDocument.URI))
defer done()
// TODO(rfindley): definition requests should be multiplexed across all views.
fh, snapshot, release, err := s.fileOf(ctx, params.TextDocument.URI)
if err != nil {
return nil, err
}
defer release()
switch kind := snapshot.FileKind(fh); kind {
case file.Tmpl:
return template.Definition(snapshot, fh, params.Position)
case file.Go:
return golang.Definition(ctx, snapshot, fh, params.Position)
default:
return nil, fmt.Errorf("can't find definitions for file type %s", kind)
}
}
func (s *server) TypeDefinition(ctx context.Context, params *protocol.TypeDefinitionParams) ([]protocol.Location, error) {
ctx, done := event.Start(ctx, "lsp.Server.typeDefinition", label.URI.Of(params.TextDocument.URI))
defer done()
// TODO(rfindley): type definition requests should be multiplexed across all views.
fh, snapshot, release, err := s.fileOf(ctx, params.TextDocument.URI)
if err != nil {
return nil, err
}
defer release()
switch kind := snapshot.FileKind(fh); kind {
case file.Go:
return golang.TypeDefinition(ctx, snapshot, fh, params.Position)
default:
return nil, fmt.Errorf("can't find type definitions for file type %s", kind)
}
}
| tools/gopls/internal/server/definition.go/0 | {
"file_path": "tools/gopls/internal/server/definition.go",
"repo_id": "tools",
"token_count": 714
} | 746 |
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package server defines gopls' implementation of the LSP server
// interface, [protocol.Server]. Call [New] to create an instance.
package server
import (
"context"
"crypto/rand"
"embed"
"encoding/base64"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
paths "path"
"strconv"
"strings"
"sync"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/cache/metadata"
"golang.org/x/tools/gopls/internal/golang"
"golang.org/x/tools/gopls/internal/progress"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/settings"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/internal/event"
)
// New creates an LSP server and binds it to handle incoming client
// messages on the supplied stream.
func New(session *cache.Session, client protocol.ClientCloser, options *settings.Options) protocol.Server {
const concurrentAnalyses = 1
// If this assignment fails to compile after a protocol
// upgrade, it means that one or more new methods need new
// stub declarations in unimplemented.go.
return &server{
diagnostics: make(map[protocol.DocumentURI]*fileDiagnostics),
watchedGlobPatterns: nil, // empty
changedFiles: make(map[protocol.DocumentURI]unit),
session: session,
client: client,
diagnosticsSema: make(chan unit, concurrentAnalyses),
progress: progress.NewTracker(client),
options: options,
viewsToDiagnose: make(map[*cache.View]uint64),
}
}
type serverState int
const (
serverCreated = serverState(iota)
serverInitializing // set once the server has received "initialize" request
serverInitialized // set once the server has received "initialized" request
serverShutDown
)
func (s serverState) String() string {
switch s {
case serverCreated:
return "created"
case serverInitializing:
return "initializing"
case serverInitialized:
return "initialized"
case serverShutDown:
return "shutDown"
}
return fmt.Sprintf("(unknown state: %d)", int(s))
}
// server implements the protocol.server interface.
type server struct {
client protocol.ClientCloser
stateMu sync.Mutex
state serverState
// notifications generated before serverInitialized
notifications []*protocol.ShowMessageParams
session *cache.Session
tempDir string
// changedFiles tracks files for which there has been a textDocument/didChange.
changedFilesMu sync.Mutex
changedFiles map[protocol.DocumentURI]unit
// folders is only valid between initialize and initialized, and holds the
// set of folders to build views for when we are ready.
// Only the valid, non-empty 'file'-scheme URIs will be added.
pendingFolders []protocol.WorkspaceFolder
// watchedGlobPatterns is the set of glob patterns that we have requested
// the client watch on disk. It will be updated as the set of directories
// that the server should watch changes.
// The map field may be reassigned but the map is immutable.
watchedGlobPatternsMu sync.Mutex
watchedGlobPatterns map[protocol.RelativePattern]unit
watchRegistrationCount int
diagnosticsMu sync.Mutex // guards map and its values
diagnostics map[protocol.DocumentURI]*fileDiagnostics
// diagnosticsSema limits the concurrency of diagnostics runs, which can be
// expensive.
diagnosticsSema chan unit
progress *progress.Tracker
// When the workspace fails to load, we show its status through a progress
// report with an error message.
criticalErrorStatusMu sync.Mutex
criticalErrorStatus *progress.WorkDone
// Track an ongoing CPU profile created with the StartProfile command and
// terminated with the StopProfile command.
ongoingProfileMu sync.Mutex
ongoingProfile *os.File // if non-nil, an ongoing profile is writing to this file
// Track most recently requested options.
optionsMu sync.Mutex
options *settings.Options
// Track the most recent completion results, for measuring completion efficacy
efficacyMu sync.Mutex
efficacyURI protocol.DocumentURI
efficacyVersion int32
efficacyItems []protocol.CompletionItem
efficacyPos protocol.Position
// Web server (for package documentation, etc) associated with this
// LSP server. Opened on demand, and closed during LSP Shutdown.
webOnce sync.Once
web *web
webErr error
// # Modification tracking and diagnostics
//
// For the purpose of tracking diagnostics, we need a monotonically
// increasing clock. Each time a change occurs on the server, this clock is
// incremented and the previous diagnostics pass is cancelled. When the
// changed is processed, the Session (via DidModifyFiles) determines which
// Views are affected by the change and these views are added to the
// viewsToDiagnose set. Then the server calls diagnoseChangedViews
// in a separate goroutine. Any Views that successfully complete their
// diagnostics are removed from the viewsToDiagnose set, provided they haven't
// been subsequently marked for re-diagnosis (as determined by the latest
// modificationID referenced by viewsToDiagnose).
//
// In this way, we enforce eventual completeness of the diagnostic set: any
// views requiring diagnosis are diagnosed, though possibly at a later point
// in time. Notably, the logic in Session.DidModifyFiles to determines if a
// view needs diagnosis considers whether any packages in the view were
// invalidated. Consider the following sequence of snapshots for a given view
// V:
//
// C1 C2
// S1 -> S2 -> S3
//
// In this case, suppose that S1 was fully type checked, and then two changes
// C1 and C2 occur in rapid succession, to a file in their package graph but
// perhaps not enclosed by V's root. In this case, the logic of
// DidModifyFiles will detect that V needs to be reloaded following C1. In
// order for our eventual consistency to be sound, we need to avoid the race
// where S2 is being diagnosed, C2 arrives, and S3 is not detected as needing
// diagnosis because the relevant package has not yet been computed in S2. To
// achieve this, we only remove V from viewsToDiagnose if the diagnosis of S2
// completes before C2 is processed, which we can confirm by checking
// S2.BackgroundContext().
modificationMu sync.Mutex
cancelPrevDiagnostics func()
viewsToDiagnose map[*cache.View]uint64 // View -> modification at which it last required diagnosis
lastModificationID uint64 // incrementing clock
}
func (s *server) WorkDoneProgressCancel(ctx context.Context, params *protocol.WorkDoneProgressCancelParams) error {
ctx, done := event.Start(ctx, "lsp.Server.workDoneProgressCancel")
defer done()
return s.progress.Cancel(params.Token)
}
// web encapsulates the web server associated with an LSP server.
// It is used for package documentation and other queries
// where HTML makes more sense than a client editor UI.
//
// Example URL:
//
// http://127.0.0.1:PORT/gopls/SECRET/...
//
// where
// - PORT is the random port number;
// - "gopls" helps the reader guess which program is the server;
// - SECRET is the 64-bit token; and
// - ... is the material part of the endpoint.
//
// Valid endpoints:
//
// open?file=%s&line=%d&col=%d - open a file
// pkg/PKGPATH?view=%s - show doc for package in a given view
// assembly?pkg=%s&view=%s&symbol=%s - show assembly of specified func symbol
// freesymbols?file=%s&range=%d:%d:%d:%d:&view=%s - show report of free symbols
type web struct {
server *http.Server
addr url.URL // "http://127.0.0.1:PORT/gopls/SECRET"
mux *http.ServeMux
}
// getWeb returns the web server associated with this
// LSP server, creating it on first request.
func (s *server) getWeb() (*web, error) {
s.webOnce.Do(func() {
s.web, s.webErr = s.initWeb()
})
return s.web, s.webErr
}
// initWeb starts the local web server through which gopls
// serves package documentation and suchlike.
//
// Clients should use [getWeb].
func (s *server) initWeb() (*web, error) {
// Use 64 random bits as the base of the URL namespace.
// This ensures that URLs are unguessable to any local
// processes that connect to the server, preventing
// exfiltration of source code.
//
// (Note: depending on the LSP client, URLs that are passed to
// it via showDocument and that result in the opening of a
// browser tab may be transiently published through the argv
// array of the open(1) or xdg-open(1) command.)
token := make([]byte, 8)
if _, err := rand.Read(token); err != nil {
return nil, fmt.Errorf("generating secret token: %v", err)
}
// Pick any free port.
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, err
}
// -- There should be no early returns after this point. --
// The root mux is not authenticated.
rootMux := http.NewServeMux()
rootMux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
http.Error(w, "request URI lacks authentication segment", http.StatusUnauthorized)
})
rootMux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, "/assets/favicon.ico", http.StatusMovedPermanently)
})
rootMux.HandleFunc("/hang", func(w http.ResponseWriter, req *http.Request) {
// This endpoint hangs until cancelled.
// It is used by JS to detect server disconnect.
<-req.Context().Done()
})
rootMux.Handle("/assets/", http.FileServer(http.FS(assets)))
secret := "/gopls/" + base64.RawURLEncoding.EncodeToString(token)
webMux := http.NewServeMux()
rootMux.Handle(secret+"/", withPanicHandler(http.StripPrefix(secret, webMux)))
webServer := &http.Server{Addr: listener.Addr().String(), Handler: rootMux}
go func() {
// This should run until LSP Shutdown, at which point
// it will return ErrServerClosed. Any other error
// means it failed to start.
if err := webServer.Serve(listener); err != nil {
if err != http.ErrServerClosed {
log.Print(err)
}
}
}()
web := &web{
server: webServer,
addr: url.URL{Scheme: "http", Host: webServer.Addr, Path: secret},
mux: webMux,
}
// The /src handler allows the browser to request that the
// LSP client editor open a file; see web.SrcURL.
webMux.HandleFunc("/src", func(w http.ResponseWriter, req *http.Request) {
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
uri := protocol.URIFromPath(req.Form.Get("file"))
line, _ := strconv.Atoi(req.Form.Get("line")) // 1-based
col, _ := strconv.Atoi(req.Form.Get("col")) // 1-based UTF-8
posn := protocol.Position{
Line: uint32(line - 1),
Character: uint32(col - 1), // TODO(adonovan): map to UTF-16
}
openClientEditor(req.Context(), s.client, protocol.Location{
URI: uri,
Range: protocol.Range{Start: posn, End: posn},
})
})
// The /pkg/PATH&view=... handler shows package documentation for PATH.
webMux.Handle("/pkg/", http.StripPrefix("/pkg/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get snapshot of specified view.
view, err := s.session.View(req.Form.Get("view"))
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
snapshot, release, err := view.Snapshot()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer release()
// Find package by path.
var found *metadata.Package
for _, mp := range snapshot.MetadataGraph().Packages {
if string(mp.PkgPath) == req.URL.Path && mp.ForTest == "" {
found = mp
break
}
}
if found == nil {
// TODO(adonovan): what should we do for external test packages?
http.Error(w, "package not found", http.StatusNotFound)
return
}
// Type-check the package and render its documentation.
pkgs, err := snapshot.TypeCheck(ctx, found.ID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
content, err := golang.PackageDocHTML(view.ID(), pkgs[0], web)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(content)
})))
// The /freesymbols?file=...&range=...&view=... handler shows
// free symbols referenced by the selection.
webMux.HandleFunc("/freesymbols", func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get snapshot of specified view.
view, err := s.session.View(req.Form.Get("view"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
snapshot, release, err := view.Snapshot()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer release()
// Get selection range and type-check.
loc := protocol.Location{
URI: protocol.DocumentURI(req.Form.Get("file")),
}
if _, err := fmt.Sscanf(req.Form.Get("range"), "%d:%d:%d:%d",
&loc.Range.Start.Line,
&loc.Range.Start.Character,
&loc.Range.End.Line,
&loc.Range.End.Character,
); err != nil {
http.Error(w, "invalid range", http.StatusInternalServerError)
return
}
pkg, pgf, err := golang.NarrowestPackageForFile(ctx, snapshot, loc.URI)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
start, end, err := pgf.RangePos(loc.Range)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Produce report.
html := golang.FreeSymbolsHTML(view.ID(), pkg, pgf, start, end, web)
w.Write(html)
})
// The /assembly?pkg=...&view=...&symbol=... handler shows
// the assembly of the current function.
webMux.HandleFunc("/assembly", func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get parameters.
var (
viewID = req.Form.Get("view")
pkgID = metadata.PackageID(req.Form.Get("pkg"))
symbol = req.Form.Get("symbol")
)
if viewID == "" || pkgID == "" || symbol == "" {
http.Error(w, "/assembly requires view, pkg, symbol", http.StatusBadRequest)
return
}
// Get snapshot of specified view.
view, err := s.session.View(viewID)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
snapshot, release, err := view.Snapshot()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer release()
pkgs, err := snapshot.TypeCheck(ctx, pkgID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pkg := pkgs[0]
// Produce report.
html, err := golang.AssemblyHTML(ctx, snapshot, pkg, symbol, web)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(html)
})
return web, nil
}
// assets holds our static web server content.
//
//go:embed assets/*
var assets embed.FS
// SrcURL returns a /src URL that, when visited, causes the client
// editor to open the specified file/line/column (in 1-based UTF-8
// coordinates).
//
// (Rendering may generate hundreds of positions across files of many
// packages, so don't convert to LSP coordinates yet: wait until the
// URL is opened.)
func (w *web) SrcURL(filename string, line, col8 int) protocol.URI {
return w.url(
"src",
fmt.Sprintf("file=%s&line=%d&col=%d", url.QueryEscape(filename), line, col8),
"")
}
// PkgURL returns a /pkg URL for the documentation of the specified package.
// The optional fragment must be of the form "Println" or "Buffer.WriteString".
func (w *web) PkgURL(viewID string, path golang.PackagePath, fragment string) protocol.URI {
return w.url(
"pkg/"+string(path),
"view="+url.QueryEscape(viewID),
fragment)
}
// freesymbolsURL returns a /freesymbols URL for a report
// on the free symbols referenced within the selection span (loc).
func (w *web) freesymbolsURL(viewID string, loc protocol.Location) protocol.URI {
return w.url(
"freesymbols",
fmt.Sprintf("file=%s&range=%d:%d:%d:%d&view=%s",
url.QueryEscape(string(loc.URI)),
loc.Range.Start.Line,
loc.Range.Start.Character,
loc.Range.End.Line,
loc.Range.End.Character,
url.QueryEscape(viewID)),
"")
}
// assemblyURL returns the URL of an assembly listing of the specified function symbol.
func (w *web) assemblyURL(viewID, packageID, symbol string) protocol.URI {
return w.url(
"assembly",
fmt.Sprintf("view=%s&pkg=%s&symbol=%s",
url.QueryEscape(viewID),
url.QueryEscape(packageID),
url.QueryEscape(symbol)),
"")
}
// url returns a URL by joining a relative path, an (encoded) query,
// and an (unencoded) fragment onto the authenticated base URL of the
// web server.
func (w *web) url(path, query, fragment string) protocol.URI {
url2 := w.addr
url2.Path = paths.Join(url2.Path, strings.TrimPrefix(path, "/"))
url2.RawQuery = query
url2.Fragment = fragment
return protocol.URI(url2.String())
}
// withPanicHandler wraps an HTTP handler with telemetry-reporting of
// panics that would otherwise be silently recovered by the net/http
// root handler.
func withPanicHandler(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
panicked := true
defer func() {
if panicked {
bug.Report("panic in HTTP handler")
}
}()
h.ServeHTTP(w, req)
panicked = false
}
}
| tools/gopls/internal/server/server.go/0 | {
"file_path": "tools/gopls/internal/server/server.go",
"repo_id": "tools",
"token_count": 6136
} | 747 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package settings
import (
"reflect"
"testing"
"time"
)
func TestDefaultsEquivalence(t *testing.T) {
opts1 := DefaultOptions()
opts2 := DefaultOptions()
if !reflect.DeepEqual(opts1, opts2) {
t.Fatal("default options are not equivalent using reflect.DeepEqual")
}
}
func TestSetOption(t *testing.T) {
type testCase struct {
name string
value any
wantError bool
check func(Options) bool
}
tests := []testCase{
{
name: "symbolStyle",
value: "Dynamic",
check: func(o Options) bool { return o.SymbolStyle == DynamicSymbols },
},
{
name: "symbolStyle",
value: "",
wantError: true,
check: func(o Options) bool { return o.SymbolStyle == "" },
},
{
name: "symbolStyle",
value: false,
wantError: true,
check: func(o Options) bool { return o.SymbolStyle == "" },
},
{
name: "symbolMatcher",
value: "caseInsensitive",
check: func(o Options) bool { return o.SymbolMatcher == SymbolCaseInsensitive },
},
{
name: "completionBudget",
value: "2s",
check: func(o Options) bool { return o.CompletionBudget == 2*time.Second },
},
{
name: "codelenses",
value: map[string]any{"generate": true},
check: func(o Options) bool { return o.Codelenses["generate"] },
},
{
name: "allExperiments",
value: true,
check: func(o Options) bool {
return true // just confirm that we handle this setting
},
},
{
name: "hoverKind",
value: "FullDocumentation",
check: func(o Options) bool {
return o.HoverKind == FullDocumentation
},
},
{
name: "hoverKind",
value: "NoDocumentation",
check: func(o Options) bool {
return o.HoverKind == NoDocumentation
},
},
{
name: "hoverKind",
value: "SingleLine",
check: func(o Options) bool {
return o.HoverKind == SingleLine
},
},
{
name: "hoverKind",
value: "Structured",
check: func(o Options) bool {
return o.HoverKind == Structured
},
},
{
name: "ui.documentation.hoverKind",
value: "Structured",
check: func(o Options) bool {
return o.HoverKind == Structured
},
},
{
name: "matcher",
value: "Fuzzy",
check: func(o Options) bool {
return o.Matcher == Fuzzy
},
},
{
name: "matcher",
value: "CaseSensitive",
check: func(o Options) bool {
return o.Matcher == CaseSensitive
},
},
{
name: "matcher",
value: "CaseInsensitive",
check: func(o Options) bool {
return o.Matcher == CaseInsensitive
},
},
{
name: "env",
value: map[string]any{"testing": "true"},
check: func(o Options) bool {
v, found := o.Env["testing"]
return found && v == "true"
},
},
{
name: "env",
value: []string{"invalid", "input"},
wantError: true,
check: func(o Options) bool {
return o.Env == nil
},
},
{
name: "directoryFilters",
value: []any{"-node_modules", "+project_a"},
check: func(o Options) bool {
return len(o.DirectoryFilters) == 2
},
},
{
name: "directoryFilters",
value: []any{"invalid"},
wantError: true,
check: func(o Options) bool {
return len(o.DirectoryFilters) == 0
},
},
{
name: "directoryFilters",
value: []string{"-invalid", "+type"},
wantError: true,
check: func(o Options) bool {
return len(o.DirectoryFilters) == 0
},
},
{
name: "annotations",
value: map[string]any{
"Nil": false,
"noBounds": true,
},
wantError: true,
check: func(o Options) bool {
return !o.Annotations[Nil] && !o.Annotations[Bounds]
},
},
{
name: "vulncheck",
value: []any{"invalid"},
wantError: true,
check: func(o Options) bool {
return o.Vulncheck == "" // For invalid value, default to 'off'.
},
},
{
name: "vulncheck",
value: "Imports",
check: func(o Options) bool {
return o.Vulncheck == ModeVulncheckImports // For invalid value, default to 'off'.
},
},
{
name: "vulncheck",
value: "imports",
check: func(o Options) bool {
return o.Vulncheck == ModeVulncheckImports
},
},
}
if !StaticcheckSupported {
tests = append(tests, testCase{
name: "staticcheck",
value: true,
check: func(o Options) bool { return o.Staticcheck == true },
wantError: true, // o.StaticcheckSupported is unset
})
}
for _, test := range tests {
var opts Options
err := opts.set(test.name, test.value, make(map[string]struct{}))
if err != nil {
if !test.wantError {
t.Errorf("Options.set(%q, %v) failed: %v",
test.name, test.value, err)
}
continue
} else if test.wantError {
t.Fatalf("Options.set(%q, %v) succeeded unexpectedly",
test.name, test.value)
}
// TODO: this could be made much better using cmp.Diff, if that becomes
// available in this module.
if !test.check(opts) {
t.Errorf("Options.set(%q, %v): unexpected result %+v", test.name, test.value, opts)
}
}
}
| tools/gopls/internal/settings/settings_test.go/0 | {
"file_path": "tools/gopls/internal/settings/settings_test.go",
"repo_id": "tools",
"token_count": 2262
} | 748 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bench
import (
"flag"
"fmt"
"sync/atomic"
"testing"
"golang.org/x/tools/gopls/internal/protocol"
. "golang.org/x/tools/gopls/internal/test/integration"
"golang.org/x/tools/gopls/internal/test/integration/fake"
)
var completionGOPATH = flag.String("completion_gopath", "", "if set, use this GOPATH for BenchmarkCompletion")
type completionBenchOptions struct {
file, locationRegexp string
// Hooks to run edits before initial completion
setup func(*Env) // run before the benchmark starts
beforeCompletion func(*Env) // run before each completion
}
// Deprecated: new tests should be expressed in BenchmarkCompletion.
func benchmarkCompletion(options completionBenchOptions, b *testing.B) {
repo := getRepo(b, "tools")
_ = repo.sharedEnv(b) // ensure cache is warm
env := repo.newEnv(b, fake.EditorConfig{}, "completion", false)
defer env.Close()
// Run edits required for this completion.
if options.setup != nil {
options.setup(env)
}
// Run a completion to make sure the system is warm.
loc := env.RegexpSearch(options.file, options.locationRegexp)
completions := env.Completion(loc)
if testing.Verbose() {
fmt.Println("Results:")
for i := 0; i < len(completions.Items); i++ {
fmt.Printf("\t%d. %v\n", i, completions.Items[i])
}
}
b.Run("tools", func(b *testing.B) {
if stopAndRecord := startProfileIfSupported(b, env, qualifiedName("tools", "completion")); stopAndRecord != nil {
defer stopAndRecord()
}
for i := 0; i < b.N; i++ {
if options.beforeCompletion != nil {
options.beforeCompletion(env)
}
env.Completion(loc)
}
})
}
// endRangeInBuffer returns the position for last character in the buffer for
// the given file.
func endRangeInBuffer(env *Env, name string) protocol.Range {
buffer := env.BufferText(name)
m := protocol.NewMapper("", []byte(buffer))
rng, err := m.OffsetRange(len(buffer), len(buffer))
if err != nil {
env.T.Fatal(err)
}
return rng
}
// Benchmark struct completion in tools codebase.
func BenchmarkStructCompletion(b *testing.B) {
file := "internal/lsp/cache/session.go"
setup := func(env *Env) {
env.OpenFile(file)
env.EditBuffer(file, protocol.TextEdit{
Range: endRangeInBuffer(env, file),
NewText: "\nvar testVariable map[string]bool = Session{}.\n",
})
}
benchmarkCompletion(completionBenchOptions{
file: file,
locationRegexp: `var testVariable map\[string\]bool = Session{}(\.)`,
setup: setup,
}, b)
}
// Benchmark import completion in tools codebase.
func BenchmarkImportCompletion(b *testing.B) {
const file = "internal/lsp/source/completion/completion.go"
benchmarkCompletion(completionBenchOptions{
file: file,
locationRegexp: `go\/()`,
setup: func(env *Env) { env.OpenFile(file) },
}, b)
}
// Benchmark slice completion in tools codebase.
func BenchmarkSliceCompletion(b *testing.B) {
file := "internal/lsp/cache/session.go"
setup := func(env *Env) {
env.OpenFile(file)
env.EditBuffer(file, protocol.TextEdit{
Range: endRangeInBuffer(env, file),
NewText: "\nvar testVariable []byte = \n",
})
}
benchmarkCompletion(completionBenchOptions{
file: file,
locationRegexp: `var testVariable \[\]byte (=)`,
setup: setup,
}, b)
}
// Benchmark deep completion in function call in tools codebase.
func BenchmarkFuncDeepCompletion(b *testing.B) {
file := "internal/lsp/source/completion/completion.go"
fileContent := `
func (c *completer) _() {
c.inference.kindMatches(c.)
}
`
setup := func(env *Env) {
env.OpenFile(file)
originalBuffer := env.BufferText(file)
env.EditBuffer(file, protocol.TextEdit{
Range: endRangeInBuffer(env, file),
// TODO(rfindley): this is a bug: it should just be fileContent.
NewText: originalBuffer + fileContent,
})
}
benchmarkCompletion(completionBenchOptions{
file: file,
locationRegexp: `func \(c \*completer\) _\(\) {\n\tc\.inference\.kindMatches\((c)`,
setup: setup,
}, b)
}
type completionTest struct {
repo string
name string
file string // repo-relative file to create
content string // file content
locationRegexp string // regexp for completion
}
var completionTests = []completionTest{
{
"tools",
"selector",
"internal/lsp/source/completion/completion2.go",
`
package completion
func (c *completer) _() {
c.inference.kindMatches(c.)
}
`,
`func \(c \*completer\) _\(\) {\n\tc\.inference\.kindMatches\((c)`,
},
{
"tools",
"unimportedident",
"internal/lsp/source/completion/completion2.go",
`
package completion
func (c *completer) _() {
lo
}
`,
`lo()`,
},
{
"tools",
"unimportedselector",
"internal/lsp/source/completion/completion2.go",
`
package completion
func (c *completer) _() {
log.
}
`,
`log\.()`,
},
{
"kubernetes",
"selector",
"pkg/kubelet/kubelet2.go",
`
package kubelet
func (kl *Kubelet) _() {
kl.
}
`,
`kl\.()`,
},
{
"kubernetes",
"identifier",
"pkg/kubelet/kubelet2.go",
`
package kubelet
func (kl *Kubelet) _() {
k // here
}
`,
`k() // here`,
},
{
"oracle",
"selector",
"dataintegration/pivot2.go",
`
package dataintegration
func (p *Pivot) _() {
p.
}
`,
`p\.()`,
},
}
// Benchmark completion following an arbitrary edit.
//
// Edits force type-checked packages to be invalidated, so we want to measure
// how long it takes before completion results are available.
func BenchmarkCompletion(b *testing.B) {
for _, test := range completionTests {
b.Run(fmt.Sprintf("%s_%s", test.repo, test.name), func(b *testing.B) {
for _, followingEdit := range []bool{true, false} {
b.Run(fmt.Sprintf("edit=%v", followingEdit), func(b *testing.B) {
for _, completeUnimported := range []bool{true, false} {
b.Run(fmt.Sprintf("unimported=%v", completeUnimported), func(b *testing.B) {
for _, budget := range []string{"0s", "100ms"} {
b.Run(fmt.Sprintf("budget=%s", budget), func(b *testing.B) {
runCompletion(b, test, followingEdit, completeUnimported, budget)
})
}
})
}
})
}
})
}
}
// For optimizing unimported completion, it can be useful to benchmark with a
// huge GOMODCACHE.
var gomodcache = flag.String("gomodcache", "", "optional GOMODCACHE for unimported completion benchmarks")
func runCompletion(b *testing.B, test completionTest, followingEdit, completeUnimported bool, budget string) {
repo := getRepo(b, test.repo)
gopath := *completionGOPATH
if gopath == "" {
// use a warm GOPATH
sharedEnv := repo.sharedEnv(b)
gopath = sharedEnv.Sandbox.GOPATH()
}
envvars := map[string]string{
"GOPATH": gopath,
}
if *gomodcache != "" {
envvars["GOMODCACHE"] = *gomodcache
}
env := repo.newEnv(b, fake.EditorConfig{
Env: envvars,
Settings: map[string]interface{}{
"completeUnimported": completeUnimported,
"completionBudget": budget,
},
}, "completion", false)
defer env.Close()
env.CreateBuffer(test.file, "// __TEST_PLACEHOLDER_0__\n"+test.content)
editPlaceholder := func() {
edits := atomic.AddInt64(&editID, 1)
env.EditBuffer(test.file, protocol.TextEdit{
Range: protocol.Range{
Start: protocol.Position{Line: 0, Character: 0},
End: protocol.Position{Line: 1, Character: 0},
},
// Increment the placeholder text, to ensure cache misses.
NewText: fmt.Sprintf("// __TEST_PLACEHOLDER_%d__\n", edits),
})
}
env.AfterChange()
// Run a completion to make sure the system is warm.
loc := env.RegexpSearch(test.file, test.locationRegexp)
completions := env.Completion(loc)
if testing.Verbose() {
fmt.Println("Results:")
for i, item := range completions.Items {
fmt.Printf("\t%d. %v\n", i, item)
}
}
b.ResetTimer()
if stopAndRecord := startProfileIfSupported(b, env, qualifiedName(test.repo, "completion")); stopAndRecord != nil {
defer stopAndRecord()
}
for i := 0; i < b.N; i++ {
if followingEdit {
editPlaceholder()
}
loc := env.RegexpSearch(test.file, test.locationRegexp)
env.Completion(loc)
}
}
| tools/gopls/internal/test/integration/bench/completion_test.go/0 | {
"file_path": "tools/gopls/internal/test/integration/bench/completion_test.go",
"repo_id": "tools",
"token_count": 3270
} | 749 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package codelens
import (
"runtime"
"testing"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/protocol/command"
"golang.org/x/tools/gopls/internal/server"
. "golang.org/x/tools/gopls/internal/test/integration"
"golang.org/x/tools/gopls/internal/test/integration/fake"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/internal/testenv"
)
func TestGCDetails_Toggle(t *testing.T) {
if runtime.GOOS == "android" {
t.Skipf("the gc details code lens doesn't work on Android")
}
// The overlay portion of the test fails with go1.19.
// I'm not sure why and not inclined to investigate.
testenv.NeedsGo1Point(t, 20)
const mod = `
-- go.mod --
module mod.com
go 1.15
-- main.go --
package main
import "fmt"
func main() {
fmt.Println(42)
}
`
WithOptions(
Settings{
"codelenses": map[string]bool{
"gc_details": true,
},
},
).Run(t, mod, func(t *testing.T, env *Env) {
env.OpenFile("main.go")
env.ExecuteCodeLensCommand("main.go", command.GCDetails, nil)
env.OnceMet(
CompletedWork(server.DiagnosticWorkTitle(server.FromToggleGCDetails), 1, true),
Diagnostics(
ForFile("main.go"),
WithMessage("42 escapes"),
WithSeverityTags("optimizer details", protocol.SeverityInformation, nil),
),
)
// GCDetails diagnostics should be reported even on unsaved
// edited buffers, thanks to the magic of overlays.
env.SetBufferContent("main.go", `
package main
func main() {}
func f(x int) *int { return &x }`)
env.AfterChange(Diagnostics(
ForFile("main.go"),
WithMessage("x escapes"),
WithSeverityTags("optimizer details", protocol.SeverityInformation, nil),
))
// Toggle the GC details code lens again so now it should be off.
env.ExecuteCodeLensCommand("main.go", command.GCDetails, nil)
env.OnceMet(
CompletedWork(server.DiagnosticWorkTitle(server.FromToggleGCDetails), 2, true),
NoDiagnostics(ForFile("main.go")),
)
})
}
// Test for the crasher in golang/go#54199
func TestGCDetails_NewFile(t *testing.T) {
bug.PanicOnBugs = false
const src = `
-- go.mod --
module mod.test
go 1.12
`
WithOptions(
Settings{
"codelenses": map[string]bool{
"gc_details": true,
},
},
).Run(t, src, func(t *testing.T, env *Env) {
env.CreateBuffer("p_test.go", "")
hasGCDetails := func() bool {
lenses := env.CodeLens("p_test.go") // should not crash
for _, lens := range lenses {
if lens.Command.Command == command.GCDetails.String() {
return true
}
}
return false
}
// With an empty file, we shouldn't get the gc_details codelens because
// there is nowhere to position it (it needs a package name).
if hasGCDetails() {
t.Errorf("got the gc_details codelens for an empty file")
}
// Edit to provide a package name.
env.EditBuffer("p_test.go", fake.NewEdit(0, 0, 0, 0, "package p"))
// Now we should get the gc_details codelens.
if !hasGCDetails() {
t.Errorf("didn't get the gc_details codelens for a valid non-empty Go file")
}
})
}
| tools/gopls/internal/test/integration/codelens/gcdetails_test.go/0 | {
"file_path": "tools/gopls/internal/test/integration/codelens/gcdetails_test.go",
"repo_id": "tools",
"token_count": 1259
} | 750 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package integration
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/server"
)
var (
// InitialWorkspaceLoad is an expectation that the workspace initial load has
// completed. It is verified via workdone reporting.
InitialWorkspaceLoad = CompletedWork(server.DiagnosticWorkTitle(server.FromInitialWorkspaceLoad), 1, false)
)
// A Verdict is the result of checking an expectation against the current
// editor state.
type Verdict int
// Order matters for the following constants: verdicts are sorted in order of
// decisiveness.
const (
// Met indicates that an expectation is satisfied by the current state.
Met Verdict = iota
// Unmet indicates that an expectation is not currently met, but could be met
// in the future.
Unmet
// Unmeetable indicates that an expectation cannot be satisfied in the
// future.
Unmeetable
)
func (v Verdict) String() string {
switch v {
case Met:
return "Met"
case Unmet:
return "Unmet"
case Unmeetable:
return "Unmeetable"
}
return fmt.Sprintf("unrecognized verdict %d", v)
}
// An Expectation is an expected property of the state of the LSP client.
// The Check function reports whether the property is met.
//
// Expectations are combinators. By composing them, tests may express
// complex expectations in terms of simpler ones.
//
// TODO(rfindley): as expectations are combined, it becomes harder to identify
// why they failed. A better signature for Check would be
//
// func(State) (Verdict, string)
//
// returning a reason for the verdict that can be composed similarly to
// descriptions.
type Expectation struct {
Check func(State) Verdict
// Description holds a noun-phrase identifying what the expectation checks.
//
// TODO(rfindley): revisit existing descriptions to ensure they compose nicely.
Description string
}
// OnceMet returns an Expectation that, once the precondition is met, asserts
// that mustMeet is met.
func OnceMet(precondition Expectation, mustMeets ...Expectation) Expectation {
check := func(s State) Verdict {
switch pre := precondition.Check(s); pre {
case Unmeetable:
return Unmeetable
case Met:
for _, mustMeet := range mustMeets {
verdict := mustMeet.Check(s)
if verdict != Met {
return Unmeetable
}
}
return Met
default:
return Unmet
}
}
description := describeExpectations(mustMeets...)
return Expectation{
Check: check,
Description: fmt.Sprintf("once %q is met, must have:\n%s", precondition.Description, description),
}
}
func describeExpectations(expectations ...Expectation) string {
var descriptions []string
for _, e := range expectations {
descriptions = append(descriptions, e.Description)
}
return strings.Join(descriptions, "\n")
}
// Not inverts the sense of an expectation: a met expectation is unmet, and an
// unmet expectation is met.
func Not(e Expectation) Expectation {
check := func(s State) Verdict {
switch v := e.Check(s); v {
case Met:
return Unmet
case Unmet, Unmeetable:
return Met
default:
panic(fmt.Sprintf("unexpected verdict %v", v))
}
}
description := describeExpectations(e)
return Expectation{
Check: check,
Description: fmt.Sprintf("not: %s", description),
}
}
// AnyOf returns an expectation that is satisfied when any of the given
// expectations is met.
func AnyOf(anyOf ...Expectation) Expectation {
check := func(s State) Verdict {
for _, e := range anyOf {
verdict := e.Check(s)
if verdict == Met {
return Met
}
}
return Unmet
}
description := describeExpectations(anyOf...)
return Expectation{
Check: check,
Description: fmt.Sprintf("Any of:\n%s", description),
}
}
// AllOf expects that all given expectations are met.
//
// TODO(rfindley): the problem with these types of combinators (OnceMet, AnyOf
// and AllOf) is that we lose the information of *why* they failed: the Awaiter
// is not smart enough to look inside.
//
// Refactor the API such that the Check function is responsible for explaining
// why an expectation failed. This should allow us to significantly improve
// test output: we won't need to summarize state at all, as the verdict
// explanation itself should describe clearly why the expectation not met.
func AllOf(allOf ...Expectation) Expectation {
check := func(s State) Verdict {
verdict := Met
for _, e := range allOf {
if v := e.Check(s); v > verdict {
verdict = v
}
}
return verdict
}
description := describeExpectations(allOf...)
return Expectation{
Check: check,
Description: fmt.Sprintf("All of:\n%s", description),
}
}
// ReadDiagnostics is an Expectation that stores the current diagnostics for
// fileName in into, whenever it is evaluated.
//
// It can be used in combination with OnceMet or AfterChange to capture the
// state of diagnostics when other expectations are satisfied.
func ReadDiagnostics(fileName string, into *protocol.PublishDiagnosticsParams) Expectation {
check := func(s State) Verdict {
diags, ok := s.diagnostics[fileName]
if !ok {
return Unmeetable
}
*into = *diags
return Met
}
return Expectation{
Check: check,
Description: fmt.Sprintf("read diagnostics for %q", fileName),
}
}
// ReadAllDiagnostics is an expectation that stores all published diagnostics
// into the provided map, whenever it is evaluated.
//
// It can be used in combination with OnceMet or AfterChange to capture the
// state of diagnostics when other expectations are satisfied.
func ReadAllDiagnostics(into *map[string]*protocol.PublishDiagnosticsParams) Expectation {
check := func(s State) Verdict {
allDiags := make(map[string]*protocol.PublishDiagnosticsParams)
for name, diags := range s.diagnostics {
allDiags[name] = diags
}
*into = allDiags
return Met
}
return Expectation{
Check: check,
Description: "read all diagnostics",
}
}
// ShownDocument asserts that the client has received a
// ShowDocumentRequest for the given URI.
func ShownDocument(uri protocol.URI) Expectation {
check := func(s State) Verdict {
for _, params := range s.showDocument {
if params.URI == uri {
return Met
}
}
return Unmet
}
return Expectation{
Check: check,
Description: fmt.Sprintf("received window/showDocument for URI %s", uri),
}
}
// ShownDocuments is an expectation that appends each showDocument
// request into the provided slice, whenever it is evaluated.
//
// It can be used in combination with OnceMet or AfterChange to
// capture the set of showDocument requests when other expectations
// are satisfied.
func ShownDocuments(into *[]*protocol.ShowDocumentParams) Expectation {
check := func(s State) Verdict {
*into = append(*into, s.showDocument...)
return Met
}
return Expectation{
Check: check,
Description: "read shown documents",
}
}
// NoShownMessage asserts that the editor has not received a ShowMessage.
func NoShownMessage(subString string) Expectation {
check := func(s State) Verdict {
for _, m := range s.showMessage {
if strings.Contains(m.Message, subString) {
return Unmeetable
}
}
return Met
}
return Expectation{
Check: check,
Description: fmt.Sprintf("no ShowMessage received containing %q", subString),
}
}
// ShownMessage asserts that the editor has received a ShowMessageRequest
// containing the given substring.
func ShownMessage(containing string) Expectation {
check := func(s State) Verdict {
for _, m := range s.showMessage {
if strings.Contains(m.Message, containing) {
return Met
}
}
return Unmet
}
return Expectation{
Check: check,
Description: fmt.Sprintf("received window/showMessage containing %q", containing),
}
}
// ShownMessageRequest asserts that the editor has received a
// ShowMessageRequest with message matching the given regular expression.
func ShownMessageRequest(messageRegexp string) Expectation {
msgRE := regexp.MustCompile(messageRegexp)
check := func(s State) Verdict {
if len(s.showMessageRequest) == 0 {
return Unmet
}
for _, m := range s.showMessageRequest {
if msgRE.MatchString(m.Message) {
return Met
}
}
return Unmet
}
return Expectation{
Check: check,
Description: fmt.Sprintf("ShowMessageRequest matching %q", messageRegexp),
}
}
// DoneDiagnosingChanges expects that diagnostics are complete from common
// change notifications: didOpen, didChange, didSave, didChangeWatchedFiles,
// and didClose.
//
// This can be used when multiple notifications may have been sent, such as
// when a didChange is immediately followed by a didSave. It is insufficient to
// simply await NoOutstandingWork, because the LSP client has no control over
// when the server starts processing a notification. Therefore, we must keep
// track of
func (e *Env) DoneDiagnosingChanges() Expectation {
stats := e.Editor.Stats()
statsBySource := map[server.ModificationSource]uint64{
server.FromDidOpen: stats.DidOpen,
server.FromDidChange: stats.DidChange,
server.FromDidSave: stats.DidSave,
server.FromDidChangeWatchedFiles: stats.DidChangeWatchedFiles,
server.FromDidClose: stats.DidClose,
server.FromDidChangeConfiguration: stats.DidChangeConfiguration,
}
var expected []server.ModificationSource
for k, v := range statsBySource {
if v > 0 {
expected = append(expected, k)
}
}
// Sort for stability.
sort.Slice(expected, func(i, j int) bool {
return expected[i] < expected[j]
})
var all []Expectation
for _, source := range expected {
all = append(all, CompletedWork(server.DiagnosticWorkTitle(source), statsBySource[source], true))
}
return AllOf(all...)
}
// AfterChange expects that the given expectations will be met after all
// state-changing notifications have been processed by the server.
// Specifically, it awaits the awaits completion of the process of diagnosis
// after the following notifications, before checking the given expectations:
// - textDocument/didOpen
// - textDocument/didChange
// - textDocument/didSave
// - textDocument/didClose
// - workspace/didChangeWatchedFiles
// - workspace/didChangeConfiguration
func (e *Env) AfterChange(expectations ...Expectation) {
e.T.Helper()
e.OnceMet(
e.DoneDiagnosingChanges(),
expectations...,
)
}
// DoneWithOpen expects all didOpen notifications currently sent by the editor
// to be completely processed.
func (e *Env) DoneWithOpen() Expectation {
opens := e.Editor.Stats().DidOpen
return CompletedWork(server.DiagnosticWorkTitle(server.FromDidOpen), opens, true)
}
// StartedChange expects that the server has at least started processing all
// didChange notifications sent from the client.
func (e *Env) StartedChange() Expectation {
changes := e.Editor.Stats().DidChange
return StartedWork(server.DiagnosticWorkTitle(server.FromDidChange), changes)
}
// DoneWithChange expects all didChange notifications currently sent by the
// editor to be completely processed.
func (e *Env) DoneWithChange() Expectation {
changes := e.Editor.Stats().DidChange
return CompletedWork(server.DiagnosticWorkTitle(server.FromDidChange), changes, true)
}
// DoneWithSave expects all didSave notifications currently sent by the editor
// to be completely processed.
func (e *Env) DoneWithSave() Expectation {
saves := e.Editor.Stats().DidSave
return CompletedWork(server.DiagnosticWorkTitle(server.FromDidSave), saves, true)
}
// StartedChangeWatchedFiles expects that the server has at least started
// processing all didChangeWatchedFiles notifications sent from the client.
func (e *Env) StartedChangeWatchedFiles() Expectation {
changes := e.Editor.Stats().DidChangeWatchedFiles
return StartedWork(server.DiagnosticWorkTitle(server.FromDidChangeWatchedFiles), changes)
}
// DoneWithChangeWatchedFiles expects all didChangeWatchedFiles notifications
// currently sent by the editor to be completely processed.
func (e *Env) DoneWithChangeWatchedFiles() Expectation {
changes := e.Editor.Stats().DidChangeWatchedFiles
return CompletedWork(server.DiagnosticWorkTitle(server.FromDidChangeWatchedFiles), changes, true)
}
// DoneWithClose expects all didClose notifications currently sent by the
// editor to be completely processed.
func (e *Env) DoneWithClose() Expectation {
changes := e.Editor.Stats().DidClose
return CompletedWork(server.DiagnosticWorkTitle(server.FromDidClose), changes, true)
}
// StartedWork expect a work item to have been started >= atLeast times.
//
// See CompletedWork.
func StartedWork(title string, atLeast uint64) Expectation {
check := func(s State) Verdict {
if s.startedWork[title] >= atLeast {
return Met
}
return Unmet
}
return Expectation{
Check: check,
Description: fmt.Sprintf("started work %q at least %d time(s)", title, atLeast),
}
}
// CompletedWork expects a work item to have been completed >= atLeast times.
//
// Since the Progress API doesn't include any hidden metadata, we must use the
// progress notification title to identify the work we expect to be completed.
func CompletedWork(title string, count uint64, atLeast bool) Expectation {
check := func(s State) Verdict {
completed := s.completedWork[title]
if completed == count || atLeast && completed > count {
return Met
}
return Unmet
}
desc := fmt.Sprintf("completed work %q %v times", title, count)
if atLeast {
desc = fmt.Sprintf("completed work %q at least %d time(s)", title, count)
}
return Expectation{
Check: check,
Description: desc,
}
}
type WorkStatus struct {
// Last seen message from either `begin` or `report` progress.
Msg string
// Message sent with `end` progress message.
EndMsg string
}
// CompletedProgress expects that workDone progress is complete for the given
// progress token. When non-nil WorkStatus is provided, it will be filled
// when the expectation is met.
//
// If the token is not a progress token that the client has seen, this
// expectation is Unmeetable.
func CompletedProgress(token protocol.ProgressToken, into *WorkStatus) Expectation {
check := func(s State) Verdict {
work, ok := s.work[token]
if !ok {
return Unmeetable // TODO(rfindley): refactor to allow the verdict to explain this result
}
if work.complete {
if into != nil {
into.Msg = work.msg
into.EndMsg = work.endMsg
}
return Met
}
return Unmet
}
desc := fmt.Sprintf("completed work for token %v", token)
return Expectation{
Check: check,
Description: desc,
}
}
// OutstandingWork expects a work item to be outstanding. The given title must
// be an exact match, whereas the given msg must only be contained in the work
// item's message.
func OutstandingWork(title, msg string) Expectation {
check := func(s State) Verdict {
for _, work := range s.work {
if work.complete {
continue
}
if work.title == title && strings.Contains(work.msg, msg) {
return Met
}
}
return Unmet
}
return Expectation{
Check: check,
Description: fmt.Sprintf("outstanding work: %q containing %q", title, msg),
}
}
// NoOutstandingWork asserts that there is no work initiated using the LSP
// $/progress API that has not completed.
//
// If non-nil, the ignore func is used to ignore certain work items for the
// purpose of this check.
//
// TODO(rfindley): consider refactoring to treat outstanding work the same way
// we treat diagnostics: with an algebra of filters.
func NoOutstandingWork(ignore func(title, msg string) bool) Expectation {
check := func(s State) Verdict {
for _, w := range s.work {
if w.complete {
continue
}
if w.title == "" {
// A token that has been created but not yet used.
//
// TODO(rfindley): this should be separated in the data model: until
// the "begin" notification, work should not be in progress.
continue
}
if ignore != nil && ignore(w.title, w.msg) {
continue
}
return Unmet
}
return Met
}
return Expectation{
Check: check,
Description: "no outstanding work",
}
}
// IgnoreTelemetryPromptWork may be used in conjunction with NoOutStandingWork
// to ignore the telemetry prompt.
func IgnoreTelemetryPromptWork(title, msg string) bool {
return title == server.TelemetryPromptWorkTitle
}
// NoErrorLogs asserts that the client has not received any log messages of
// error severity.
func NoErrorLogs() Expectation {
return NoLogMatching(protocol.Error, "")
}
// LogMatching asserts that the client has received a log message
// of type typ matching the regexp re a certain number of times.
//
// The count argument specifies the expected number of matching logs. If
// atLeast is set, this is a lower bound, otherwise there must be exactly count
// matching logs.
//
// Logs are asynchronous to other LSP messages, so this expectation should not
// be used with combinators such as OnceMet or AfterChange that assert on
// ordering with respect to other operations.
func LogMatching(typ protocol.MessageType, re string, count int, atLeast bool) Expectation {
rec, err := regexp.Compile(re)
if err != nil {
panic(err)
}
check := func(state State) Verdict {
var found int
for _, msg := range state.logs {
if msg.Type == typ && rec.Match([]byte(msg.Message)) {
found++
}
}
// Check for an exact or "at least" match.
if found == count || (found >= count && atLeast) {
return Met
}
// If we require an exact count, and have received more than expected, the
// expectation can never be met.
if found > count && !atLeast {
return Unmeetable
}
return Unmet
}
desc := fmt.Sprintf("log message matching %q expected %v times", re, count)
if atLeast {
desc = fmt.Sprintf("log message matching %q expected at least %v times", re, count)
}
return Expectation{
Check: check,
Description: desc,
}
}
// NoLogMatching asserts that the client has not received a log message
// of type typ matching the regexp re. If re is an empty string, any log
// message is considered a match.
func NoLogMatching(typ protocol.MessageType, re string) Expectation {
var r *regexp.Regexp
if re != "" {
var err error
r, err = regexp.Compile(re)
if err != nil {
panic(err)
}
}
check := func(state State) Verdict {
for _, msg := range state.logs {
if msg.Type != typ {
continue
}
if r == nil || r.Match([]byte(msg.Message)) {
return Unmeetable
}
}
return Met
}
return Expectation{
Check: check,
Description: fmt.Sprintf("no log message matching %q", re),
}
}
// FileWatchMatching expects that a file registration matches re.
func FileWatchMatching(re string) Expectation {
return Expectation{
Check: checkFileWatch(re, Met, Unmet),
Description: fmt.Sprintf("file watch matching %q", re),
}
}
// NoFileWatchMatching expects that no file registration matches re.
func NoFileWatchMatching(re string) Expectation {
return Expectation{
Check: checkFileWatch(re, Unmet, Met),
Description: fmt.Sprintf("no file watch matching %q", re),
}
}
func checkFileWatch(re string, onMatch, onNoMatch Verdict) func(State) Verdict {
rec := regexp.MustCompile(re)
return func(s State) Verdict {
r := s.registeredCapabilities["workspace/didChangeWatchedFiles"]
watchers := jsonProperty(r.RegisterOptions, "watchers").([]interface{})
for _, watcher := range watchers {
pattern := jsonProperty(watcher, "globPattern").(string)
if rec.MatchString(pattern) {
return onMatch
}
}
return onNoMatch
}
}
// jsonProperty extracts a value from a path of JSON property names, assuming
// the default encoding/json unmarshaling to the empty interface (i.e.: that
// JSON objects are unmarshalled as map[string]interface{})
//
// For example, if obj is unmarshalled from the following json:
//
// {
// "foo": { "bar": 3 }
// }
//
// Then jsonProperty(obj, "foo", "bar") will be 3.
func jsonProperty(obj interface{}, path ...string) interface{} {
if len(path) == 0 || obj == nil {
return obj
}
m := obj.(map[string]interface{})
return jsonProperty(m[path[0]], path[1:]...)
}
// Diagnostics asserts that there is at least one diagnostic matching the given
// filters.
func Diagnostics(filters ...DiagnosticFilter) Expectation {
check := func(s State) Verdict {
diags := flattenDiagnostics(s)
for _, filter := range filters {
var filtered []flatDiagnostic
for _, d := range diags {
if filter.check(d.name, d.diag) {
filtered = append(filtered, d)
}
}
if len(filtered) == 0 {
// TODO(rfindley): if/when expectations describe their own failure, we
// can provide more useful information here as to which filter caused
// the failure.
return Unmet
}
diags = filtered
}
return Met
}
var descs []string
for _, filter := range filters {
descs = append(descs, filter.desc)
}
return Expectation{
Check: check,
Description: "any diagnostics " + strings.Join(descs, ", "),
}
}
// NoDiagnostics asserts that there are no diagnostics matching the given
// filters. Notably, if no filters are supplied this assertion checks that
// there are no diagnostics at all, for any file.
func NoDiagnostics(filters ...DiagnosticFilter) Expectation {
check := func(s State) Verdict {
diags := flattenDiagnostics(s)
for _, filter := range filters {
var filtered []flatDiagnostic
for _, d := range diags {
if filter.check(d.name, d.diag) {
filtered = append(filtered, d)
}
}
diags = filtered
}
if len(diags) > 0 {
return Unmet
}
return Met
}
var descs []string
for _, filter := range filters {
descs = append(descs, filter.desc)
}
return Expectation{
Check: check,
Description: "no diagnostics " + strings.Join(descs, ", "),
}
}
type flatDiagnostic struct {
name string
diag protocol.Diagnostic
}
func flattenDiagnostics(state State) []flatDiagnostic {
var result []flatDiagnostic
for name, diags := range state.diagnostics {
for _, diag := range diags.Diagnostics {
result = append(result, flatDiagnostic{name, diag})
}
}
return result
}
// -- Diagnostic filters --
// A DiagnosticFilter filters the set of diagnostics, for assertion with
// Diagnostics or NoDiagnostics.
type DiagnosticFilter struct {
desc string
check func(name string, _ protocol.Diagnostic) bool
}
// ForFile filters to diagnostics matching the sandbox-relative file name.
func ForFile(name string) DiagnosticFilter {
return DiagnosticFilter{
desc: fmt.Sprintf("for file %q", name),
check: func(diagName string, _ protocol.Diagnostic) bool {
return diagName == name
},
}
}
// FromSource filters to diagnostics matching the given diagnostics source.
func FromSource(source string) DiagnosticFilter {
return DiagnosticFilter{
desc: fmt.Sprintf("with source %q", source),
check: func(_ string, d protocol.Diagnostic) bool {
return d.Source == source
},
}
}
// AtRegexp filters to diagnostics in the file with sandbox-relative path name,
// at the first position matching the given regexp pattern.
//
// TODO(rfindley): pass in the editor to expectations, so that they may depend
// on editor state and AtRegexp can be a function rather than a method.
func (e *Env) AtRegexp(name, pattern string) DiagnosticFilter {
loc := e.RegexpSearch(name, pattern)
return DiagnosticFilter{
desc: fmt.Sprintf("at the first position (%v) matching %#q in %q", loc.Range.Start, pattern, name),
check: func(diagName string, d protocol.Diagnostic) bool {
return diagName == name && d.Range.Start == loc.Range.Start
},
}
}
// AtPosition filters to diagnostics at location name:line:character, for a
// sandbox-relative path name.
//
// Line and character are 0-based, and character measures UTF-16 codes.
//
// Note: prefer the more readable AtRegexp.
func AtPosition(name string, line, character uint32) DiagnosticFilter {
pos := protocol.Position{Line: line, Character: character}
return DiagnosticFilter{
desc: fmt.Sprintf("at %s:%d:%d", name, line, character),
check: func(diagName string, d protocol.Diagnostic) bool {
return diagName == name && d.Range.Start == pos
},
}
}
// WithMessage filters to diagnostics whose message contains the given
// substring.
func WithMessage(substring string) DiagnosticFilter {
return DiagnosticFilter{
desc: fmt.Sprintf("with message containing %q", substring),
check: func(_ string, d protocol.Diagnostic) bool {
return strings.Contains(d.Message, substring)
},
}
}
// WithSeverityTags filters to diagnostics whose severity and tags match
// the given expectation.
func WithSeverityTags(diagName string, severity protocol.DiagnosticSeverity, tags []protocol.DiagnosticTag) DiagnosticFilter {
return DiagnosticFilter{
desc: fmt.Sprintf("with diagnostic %q with severity %q and tag %#q", diagName, severity, tags),
check: func(_ string, d protocol.Diagnostic) bool {
return d.Source == diagName && d.Severity == severity && cmp.Equal(d.Tags, tags)
},
}
}
| tools/gopls/internal/test/integration/expectation.go/0 | {
"file_path": "tools/gopls/internal/test/integration/expectation.go",
"repo_id": "tools",
"token_count": 8093
} | 751 |
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package misc
import (
"fmt"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/settings"
. "golang.org/x/tools/gopls/internal/test/integration"
"golang.org/x/tools/gopls/internal/util/slices"
)
// This test exercises the filtering of code actions in generated files.
// Most code actions, being potential edits, are discarded, but
// some (GoTest, GoDoc) are pure queries, and so are allowed.
func TestCodeActionsInGeneratedFiles(t *testing.T) {
const src = `
-- go.mod --
module example.com
go 1.19
-- src/a.go --
package a
func f() { g() }
func g() {}
-- gen/a.go --
// Code generated by hand; DO NOT EDIT.
package a
func f() { g() }
func g() {}
`
Run(t, src, func(t *testing.T, env *Env) {
check := func(filename string, wantKind ...protocol.CodeActionKind) {
env.OpenFile(filename)
loc := env.RegexpSearch(filename, `g\(\)`)
actions, err := env.Editor.CodeAction(env.Ctx, loc, nil, protocol.CodeActionUnknownTrigger)
if err != nil {
t.Fatal(err)
}
type kinds = map[protocol.CodeActionKind]bool
got := make(kinds)
for _, act := range actions {
got[act.Kind] = true
}
want := make(kinds)
for _, kind := range wantKind {
want[kind] = true
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("%s: unexpected CodeActionKinds: (-want +got):\n%s",
filename, diff)
t.Log(actions)
}
}
check("src/a.go",
settings.GoAssembly,
settings.GoDoc,
settings.GoFreeSymbols,
protocol.RefactorExtract,
protocol.RefactorInline)
check("gen/a.go",
settings.GoAssembly,
settings.GoDoc,
settings.GoFreeSymbols)
})
}
// Test refactor.inline is not included in automatically triggered code action
// unless users want refactoring.
func TestVSCodeIssue65167(t *testing.T) {
const vim1 = `package main
func main() {
Func() // range to be selected
}
func Func() int { return 0 }
`
Run(t, "", func(t *testing.T, env *Env) {
env.CreateBuffer("main.go", vim1)
for _, trigger := range []protocol.CodeActionTriggerKind{
protocol.CodeActionUnknownTrigger,
protocol.CodeActionInvoked,
protocol.CodeActionAutomatic,
} {
t.Run(fmt.Sprintf("trigger=%v", trigger), func(t *testing.T) {
for _, selectedRange := range []bool{false, true} {
t.Run(fmt.Sprintf("range=%t", selectedRange), func(t *testing.T) {
loc := env.RegexpSearch("main.go", "Func")
if !selectedRange {
// assume the cursor is placed at the beginning of `Func`, so end==start.
loc.Range.End = loc.Range.Start
}
actions := env.CodeAction(loc, nil, trigger)
want := trigger != protocol.CodeActionAutomatic || selectedRange
if got := slices.ContainsFunc(actions, func(act protocol.CodeAction) bool {
return act.Kind == protocol.RefactorInline
}); got != want {
t.Errorf("got refactor.inline = %t, want %t", got, want)
}
})
}
})
}
})
}
| tools/gopls/internal/test/integration/misc/codeactions_test.go/0 | {
"file_path": "tools/gopls/internal/test/integration/misc/codeactions_test.go",
"repo_id": "tools",
"token_count": 1259
} | 752 |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package misc
import (
"testing"
. "golang.org/x/tools/gopls/internal/test/integration"
)
func TestMultipleAdHocPackages(t *testing.T) {
Run(t, `
-- a/a.go --
package main
import "fmt"
func main() {
fmt.Println("")
}
-- a/b.go --
package main
import "fmt"
func main() () {
fmt.Println("")
}
`, func(t *testing.T, env *Env) {
env.OpenFile("a/a.go")
if list := env.Completion(env.RegexpSearch("a/a.go", "Println")); list == nil || len(list.Items) == 0 {
t.Fatal("expected completions, got none")
}
env.OpenFile("a/b.go")
if list := env.Completion(env.RegexpSearch("a/b.go", "Println")); list == nil || len(list.Items) == 0 {
t.Fatal("expected completions, got none")
}
if list := env.Completion(env.RegexpSearch("a/a.go", "Println")); list == nil || len(list.Items) == 0 {
t.Fatal("expected completions, got none")
}
})
}
| tools/gopls/internal/test/integration/misc/multiple_adhoc_test.go/0 | {
"file_path": "tools/gopls/internal/test/integration/misc/multiple_adhoc_test.go",
"repo_id": "tools",
"token_count": 411
} | 753 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package integration
import (
"context"
"flag"
"fmt"
"os"
"runtime"
"testing"
"time"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/cmd"
"golang.org/x/tools/internal/drivertest"
"golang.org/x/tools/internal/gocommand"
"golang.org/x/tools/internal/memoize"
"golang.org/x/tools/internal/testenv"
"golang.org/x/tools/internal/tool"
)
var (
runSubprocessTests = flag.Bool("enable_gopls_subprocess_tests", false, "run integration tests against a gopls subprocess (default: in-process)")
goplsBinaryPath = flag.String("gopls_test_binary", "", "path to the gopls binary for use as a remote, for use with the -enable_gopls_subprocess_tests flag")
timeout = flag.Duration("timeout", defaultTimeout(), "if nonzero, default timeout for each integration test; defaults to GOPLS_INTEGRATION_TEST_TIMEOUT")
skipCleanup = flag.Bool("skip_cleanup", false, "whether to skip cleaning up temp directories")
printGoroutinesOnFailure = flag.Bool("print_goroutines", false, "whether to print goroutines info on failure")
printLogs = flag.Bool("print_logs", false, "whether to print LSP logs")
)
func defaultTimeout() time.Duration {
s := os.Getenv("GOPLS_INTEGRATION_TEST_TIMEOUT")
if s == "" {
return 0
}
d, err := time.ParseDuration(s)
if err != nil {
fmt.Fprintf(os.Stderr, "invalid GOPLS_INTEGRATION_TEST_TIMEOUT %q: %v\n", s, err)
os.Exit(2)
}
return d
}
var runner *Runner
func Run(t *testing.T, files string, f TestFunc) {
runner.Run(t, files, f)
}
func WithOptions(opts ...RunOption) configuredRunner {
return configuredRunner{opts: opts}
}
type configuredRunner struct {
opts []RunOption
}
func (r configuredRunner) Run(t *testing.T, files string, f TestFunc) {
// Print a warning if the test's temporary directory is not
// suitable as a workspace folder, as this may lead to
// otherwise-cryptic failures. This situation typically occurs
// when an arbitrary string (e.g. "foo.") is used as a subtest
// name, on a platform with filename restrictions (e.g. no
// trailing period on Windows).
tmp := t.TempDir()
if err := cache.CheckPathValid(tmp); err != nil {
t.Logf("Warning: testing.T.TempDir(%s) is not valid as a workspace folder: %s",
tmp, err)
}
runner.Run(t, files, f, r.opts...)
}
// RunMultiple runs a test multiple times, with different options.
// The runner should be constructed with [WithOptions].
//
// TODO(rfindley): replace Modes with selective use of RunMultiple.
type RunMultiple []struct {
Name string
Runner interface {
Run(t *testing.T, files string, f TestFunc)
}
}
func (r RunMultiple) Run(t *testing.T, files string, f TestFunc) {
for _, runner := range r {
t.Run(runner.Name, func(t *testing.T) {
runner.Runner.Run(t, files, f)
})
}
}
// DefaultModes returns the default modes to run for each regression test (they
// may be reconfigured by the tests themselves).
func DefaultModes() Mode {
modes := Default
if !testing.Short() {
// TODO(rfindley): we should just run a few select integration tests in
// "Forwarded" mode, and call it a day. No need to run every single test in
// two ways.
modes |= Forwarded
}
if *runSubprocessTests {
modes |= SeparateProcess
}
return modes
}
var runFromMain = false // true if Main has been called
// Main sets up and tears down the shared integration test state.
func Main(m *testing.M) (code int) {
// Provide an entrypoint for tests that use a fake go/packages driver.
drivertest.RunIfChild()
defer func() {
if runner != nil {
if err := runner.Close(); err != nil {
fmt.Fprintf(os.Stderr, "closing test runner: %v\n", err)
// Cleanup is broken in go1.12 and earlier, and sometimes flakes on
// Windows due to file locking, but this is OK for our CI.
//
// Fail on go1.13+, except for windows and android which have shutdown problems.
if testenv.Go1Point() >= 13 && runtime.GOOS != "windows" && runtime.GOOS != "android" {
if code == 0 {
code = 1
}
}
}
}
}()
runFromMain = true
// golang/go#54461: enable additional debugging around hanging Go commands.
gocommand.DebugHangingGoCommands = true
// If this magic environment variable is set, run gopls instead of the test
// suite. See the documentation for runTestAsGoplsEnvvar for more details.
if os.Getenv(runTestAsGoplsEnvvar) == "true" {
tool.Main(context.Background(), cmd.New(), os.Args[1:])
return 0
}
if !testenv.HasExec() {
fmt.Printf("skipping all tests: exec not supported on %s/%s\n", runtime.GOOS, runtime.GOARCH)
return 0
}
testenv.ExitIfSmallMachine()
flag.Parse()
// Disable GOPACKAGESDRIVER, as it can cause spurious test failures.
os.Setenv("GOPACKAGESDRIVER", "off")
if skipReason := checkBuilder(); skipReason != "" {
fmt.Printf("Skipping all tests: %s\n", skipReason)
return 0
}
if err := testenv.HasTool("go"); err != nil {
fmt.Println("Missing go command")
return 1
}
runner = &Runner{
DefaultModes: DefaultModes(),
Timeout: *timeout,
PrintGoroutinesOnFailure: *printGoroutinesOnFailure,
SkipCleanup: *skipCleanup,
store: memoize.NewStore(memoize.NeverEvict),
}
runner.goplsPath = *goplsBinaryPath
if runner.goplsPath == "" {
var err error
runner.goplsPath, err = os.Executable()
if err != nil {
panic(fmt.Sprintf("finding test binary path: %v", err))
}
}
dir, err := os.MkdirTemp("", "gopls-test-")
if err != nil {
panic(fmt.Errorf("creating temp directory: %v", err))
}
runner.tempDir = dir
return m.Run()
}
| tools/gopls/internal/test/integration/regtest.go/0 | {
"file_path": "tools/gopls/internal/test/integration/regtest.go",
"repo_id": "tools",
"token_count": 2150
} | 754 |
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package workspace
import (
"testing"
. "golang.org/x/tools/gopls/internal/test/integration"
)
func TestWorkspacePackagesExcludesVendor(t *testing.T) {
// This test verifies that packages in the vendor directory are not workspace
// packages. This would be an easy mistake for gopls to make, since mod
// vendoring excludes go.mod files, and therefore the nearest go.mod file for
// vendored packages is often the workspace mod file.
const proxy = `
-- other.com/b@v1.0.0/go.mod --
module other.com/b
go 1.18
-- other.com/b@v1.0.0/b.go --
package b
type B int
func _() {
var V int // unused
}
`
const src = `
-- go.mod --
module example.com/a
go 1.14
require other.com/b v1.0.0
-- go.sum --
other.com/b v1.0.0 h1:ct1+0RPozzMvA2rSYnVvIfr/GDHcd7oVnw147okdi3g=
other.com/b v1.0.0/go.mod h1:bfTSZo/4ZtAQJWBYScopwW6n9Ctfsl2mi8nXsqjDXR8=
-- a.go --
package a
import "other.com/b"
var _ b.B
`
WithOptions(
ProxyFiles(proxy),
Modes(Default),
).Run(t, src, func(t *testing.T, env *Env) {
env.RunGoCommand("mod", "vendor")
// Uncomment for updated go.sum contents.
// env.DumpGoSum(".")
env.OpenFile("a.go")
env.AfterChange(
NoDiagnostics(), // as b is not a workspace package
)
env.GoToDefinition(env.RegexpSearch("a.go", `b\.(B)`))
env.AfterChange(
Diagnostics(env.AtRegexp("vendor/other.com/b/b.go", "V"), WithMessage("not used")),
)
})
}
| tools/gopls/internal/test/integration/workspace/vendor_test.go/0 | {
"file_path": "tools/gopls/internal/test/integration/workspace/vendor_test.go",
"repo_id": "tools",
"token_count": 634
} | 755 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The immutable package defines immutable wrappers around common data
// structures. These are used for additional type safety inside gopls.
//
// See the "persistent" package for copy-on-write data structures.
package immutable
// Map is an immutable wrapper around an ordinary Go map.
type Map[K comparable, V any] struct {
m map[K]V
}
// MapOf wraps the given Go map.
//
// The caller must not subsequently mutate the map.
func MapOf[K comparable, V any](m map[K]V) Map[K, V] {
return Map[K, V]{m}
}
// Value returns the mapped value for k.
// It is equivalent to the commaok form of an ordinary go map, and returns
// (zero, false) if the key is not present.
func (m Map[K, V]) Value(k K) (V, bool) {
v, ok := m.m[k]
return v, ok
}
// Len returns the number of entries in the Map.
func (m Map[K, V]) Len() int {
return len(m.m)
}
// Range calls f for each mapped (key, value) pair.
// There is no way to break out of the loop.
// TODO: generalize when Go iterators (#61405) land.
func (m Map[K, V]) Range(f func(k K, v V)) {
for k, v := range m.m {
f(k, v)
}
}
| tools/gopls/internal/util/immutable/immutable.go/0 | {
"file_path": "tools/gopls/internal/util/immutable/immutable.go",
"repo_id": "tools",
"token_count": 409
} | 756 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated by copying from golang.org/x/vuln@v1.0.1 (go run copier.go); DO NOT EDIT.
// Package govulncheck contains the JSON output structs for govulncheck.
package govulncheck
import (
"time"
"golang.org/x/tools/gopls/internal/vulncheck/osv"
)
const (
// ProtocolVersion is the current protocol version this file implements
ProtocolVersion = "v1.0.0"
)
// Message is an entry in the output stream. It will always have exactly one
// field filled in.
type Message struct {
Config *Config `json:"config,omitempty"`
Progress *Progress `json:"progress,omitempty"`
OSV *osv.Entry `json:"osv,omitempty"`
Finding *Finding `json:"finding,omitempty"`
}
// Config must occur as the first message of a stream and informs the client
// about the information used to generate the findings.
// The only required field is the protocol version.
type Config struct {
// ProtocolVersion specifies the version of the JSON protocol.
ProtocolVersion string `json:"protocol_version"`
// ScannerName is the name of the tool, for example, govulncheck.
//
// We expect this JSON format to be used by other tools that wrap
// govulncheck, which will have a different name.
ScannerName string `json:"scanner_name,omitempty"`
// ScannerVersion is the version of the tool.
ScannerVersion string `json:"scanner_version,omitempty"`
// DB is the database used by the tool, for example,
// vuln.go.dev.
DB string `json:"db,omitempty"`
// LastModified is the last modified time of the data source.
DBLastModified *time.Time `json:"db_last_modified,omitempty"`
// GoVersion is the version of Go used for analyzing standard library
// vulnerabilities.
GoVersion string `json:"go_version,omitempty"`
// ScanLevel instructs govulncheck to analyze at a specific level of detail.
// Valid values include module, package and symbol.
ScanLevel ScanLevel `json:"scan_level,omitempty"`
}
// Progress messages are informational only, intended to allow users to monitor
// the progress of a long running scan.
// A stream must remain fully valid and able to be interpreted with all progress
// messages removed.
type Progress struct {
// A time stamp for the message.
Timestamp *time.Time `json:"time,omitempty"`
// Message is the progress message.
Message string `json:"message,omitempty"`
}
// Vuln represents a single OSV entry.
type Finding struct {
// OSV is the id of the detected vulnerability.
OSV string `json:"osv,omitempty"`
// FixedVersion is the module version where the vulnerability was
// fixed. This is empty if a fix is not available.
//
// If there are multiple fixed versions in the OSV report, this will
// be the fixed version in the latest range event for the OSV report.
//
// For example, if the range events are
// {introduced: 0, fixed: 1.0.0} and {introduced: 1.1.0}, the fixed version
// will be empty.
//
// For the stdlib, we will show the fixed version closest to the
// Go version that is used. For example, if a fix is available in 1.17.5 and
// 1.18.5, and the GOVERSION is 1.17.3, 1.17.5 will be returned as the
// fixed version.
FixedVersion string `json:"fixed_version,omitempty"`
// Trace contains an entry for each frame in the trace.
//
// Frames are sorted starting from the imported vulnerable symbol
// until the entry point. The first frame in Frames should match
// Symbol.
//
// In binary mode, trace will contain a single-frame with no position
// information.
//
// When a package is imported but no vulnerable symbol is called, the trace
// will contain a single-frame with no symbol or position information.
Trace []*Frame `json:"trace,omitempty"`
}
// Frame represents an entry in a finding trace.
type Frame struct {
// Module is the module path of the module containing this symbol.
//
// Importable packages in the standard library will have the path "stdlib".
Module string `json:"module"`
// Version is the module version from the build graph.
Version string `json:"version,omitempty"`
// Package is the import path.
Package string `json:"package,omitempty"`
// Function is the function name.
Function string `json:"function,omitempty"`
// Receiver is the receiver type if the called symbol is a method.
//
// The client can create the final symbol name by
// prepending Receiver to FuncName.
Receiver string `json:"receiver,omitempty"`
// Position describes an arbitrary source position
// including the file, line, and column location.
// A Position is valid if the line number is > 0.
Position *Position `json:"position,omitempty"`
}
// Position represents arbitrary source position.
type Position struct {
Filename string `json:"filename,omitempty"` // filename, if any
Offset int `json:"offset"` // byte offset, starting at 0
Line int `json:"line"` // line number, starting at 1
Column int `json:"column"` // column number, starting at 1 (byte count)
}
// ScanLevel represents the detail level at which a scan occurred.
// This can be necessary to correctly interpret the findings, for instance if
// a scan is at symbol level and a finding does not have a symbol it means the
// vulnerability was imported but not called. If the scan however was at
// "package" level, that determination cannot be made.
type ScanLevel string
const (
scanLevelModule = "module"
scanLevelPackage = "package"
scanLevelSymbol = "symbol"
)
// WantSymbols can be used to check whether the scan level is one that is able
// to generate symbols called findings.
func (l ScanLevel) WantSymbols() bool { return l == scanLevelSymbol }
| tools/gopls/internal/vulncheck/govulncheck/govulncheck.go/0 | {
"file_path": "tools/gopls/internal/vulncheck/govulncheck/govulncheck.go",
"repo_id": "tools",
"token_count": 1696
} | 757 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package work
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/internal/event"
)
func Completion(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) (*protocol.CompletionList, error) {
ctx, done := event.Start(ctx, "work.Completion")
defer done()
// Get the position of the cursor.
pw, err := snapshot.ParseWork(ctx, fh)
if err != nil {
return nil, fmt.Errorf("getting go.work file handle: %w", err)
}
cursor, err := pw.Mapper.PositionOffset(position)
if err != nil {
return nil, fmt.Errorf("computing cursor offset: %w", err)
}
// Find the use statement the user is in.
use, pathStart, _ := usePath(pw, cursor)
if use == nil {
return &protocol.CompletionList{}, nil
}
completingFrom := use.Path[:cursor-pathStart]
// We're going to find the completions of the user input
// (completingFrom) by doing a walk on the innermost directory
// of the given path, and comparing the found paths to make sure
// that they match the component of the path after the
// innermost directory.
//
// We'll maintain two paths when doing this: pathPrefixSlash
// is essentially the path the user typed in, and pathPrefixAbs
// is the path made absolute from the go.work directory.
pathPrefixSlash := completingFrom
pathPrefixAbs := filepath.FromSlash(pathPrefixSlash)
if !filepath.IsAbs(pathPrefixAbs) {
pathPrefixAbs = filepath.Join(filepath.Dir(pw.URI.Path()), pathPrefixAbs)
}
// pathPrefixDir is the directory that will be walked to find matches.
// If pathPrefixSlash is not explicitly a directory boundary (is either equivalent to "." or
// ends in a separator) we need to examine its parent directory to find sibling files that
// match.
depthBound := 5
pathPrefixDir, pathPrefixBase := pathPrefixAbs, ""
pathPrefixSlashDir := pathPrefixSlash
if filepath.Clean(pathPrefixSlash) != "." && !strings.HasSuffix(pathPrefixSlash, "/") {
depthBound++
pathPrefixDir, pathPrefixBase = filepath.Split(pathPrefixAbs)
pathPrefixSlashDir = dirNonClean(pathPrefixSlash)
}
var completions []string
// Stop traversing deeper once we've hit 10k files to try to stay generally under 100ms.
const numSeenBound = 10000
var numSeen int
stopWalking := errors.New("hit numSeenBound")
err = filepath.WalkDir(pathPrefixDir, func(wpath string, entry fs.DirEntry, err error) error {
if err != nil {
// golang/go#64225: an error reading a dir is expected, as the user may
// be typing out a use directive for a directory that doesn't exist.
return nil
}
if numSeen > numSeenBound {
// Stop traversing if we hit bound.
return stopWalking
}
numSeen++
// rel is the path relative to pathPrefixDir.
// Make sure that it has pathPrefixBase as a prefix
// otherwise it won't match the beginning of the
// base component of the path the user typed in.
rel := strings.TrimPrefix(wpath[len(pathPrefixDir):], string(filepath.Separator))
if entry.IsDir() && wpath != pathPrefixDir && !strings.HasPrefix(rel, pathPrefixBase) {
return filepath.SkipDir
}
// Check for a match (a module directory).
if filepath.Base(rel) == "go.mod" {
relDir := strings.TrimSuffix(dirNonClean(rel), string(os.PathSeparator))
completionPath := join(pathPrefixSlashDir, filepath.ToSlash(relDir))
if !strings.HasPrefix(completionPath, completingFrom) {
return nil
}
if strings.HasSuffix(completionPath, "/") {
// Don't suggest paths that end in "/". This happens
// when the input is a path that ends in "/" and
// the completion is empty.
return nil
}
completion := completionPath[len(completingFrom):]
if completingFrom == "" && !strings.HasPrefix(completion, "./") {
// Bias towards "./" prefixes.
completion = join(".", completion)
}
completions = append(completions, completion)
}
if depth := strings.Count(rel, string(filepath.Separator)); depth >= depthBound {
return filepath.SkipDir
}
return nil
})
if err != nil && !errors.Is(err, stopWalking) {
return nil, fmt.Errorf("walking to find completions: %w", err)
}
sort.Strings(completions)
items := []protocol.CompletionItem{} // must be a slice
for _, c := range completions {
items = append(items, protocol.CompletionItem{
Label: c,
InsertText: c,
})
}
return &protocol.CompletionList{Items: items}, nil
}
// dirNonClean is filepath.Dir, without the Clean at the end.
func dirNonClean(path string) string {
vol := filepath.VolumeName(path)
i := len(path) - 1
for i >= len(vol) && !os.IsPathSeparator(path[i]) {
i--
}
return path[len(vol) : i+1]
}
func join(a, b string) string {
if a == "" {
return b
}
if b == "" {
return a
}
return strings.TrimSuffix(a, "/") + "/" + b
}
| tools/gopls/internal/work/completion.go/0 | {
"file_path": "tools/gopls/internal/work/completion.go",
"repo_id": "tools",
"token_count": 1800
} | 758 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// TODO: test swap corresponding types (e.g. u1 <-> u2 and u2 <-> u1)
// TODO: test exported alias refers to something in another package -- does correspondence work then?
// TODO: CODE COVERAGE
// TODO: note that we may miss correspondences because we bail early when we compare a signature (e.g. when lengths differ; we could do up to the shorter)
// TODO: if you add an unexported method to an exposed interface, you have to check that
// every exposed type that previously implemented the interface still does. Otherwise
// an external assignment of the exposed type to the interface type could fail.
// TODO: check constant values: large values aren't representable by some types.
// TODO: Document all the incompatibilities we don't check for.
package apidiff
import (
"fmt"
"go/constant"
"go/token"
"go/types"
"golang.org/x/tools/internal/aliases"
)
// Changes reports on the differences between the APIs of the old and new packages.
// It classifies each difference as either compatible or incompatible (breaking.) For
// a detailed discussion of what constitutes an incompatible change, see the package
// documentation.
func Changes(old, new *types.Package) Report {
d := newDiffer(old, new)
d.checkPackage()
r := Report{}
for _, m := range d.incompatibles.collect() {
r.Changes = append(r.Changes, Change{Message: m, Compatible: false})
}
for _, m := range d.compatibles.collect() {
r.Changes = append(r.Changes, Change{Message: m, Compatible: true})
}
return r
}
type differ struct {
old, new *types.Package
// Correspondences between named types.
// Even though it is the named types (*types.Named) that correspond, we use
// *types.TypeName as a map key because they are canonical.
// The values can be either named types or basic types.
correspondMap map[*types.TypeName]types.Type
// Messages.
incompatibles messageSet
compatibles messageSet
}
func newDiffer(old, new *types.Package) *differ {
return &differ{
old: old,
new: new,
correspondMap: map[*types.TypeName]types.Type{},
incompatibles: messageSet{},
compatibles: messageSet{},
}
}
func (d *differ) incompatible(obj types.Object, part, format string, args ...interface{}) {
addMessage(d.incompatibles, obj, part, format, args)
}
func (d *differ) compatible(obj types.Object, part, format string, args ...interface{}) {
addMessage(d.compatibles, obj, part, format, args)
}
func addMessage(ms messageSet, obj types.Object, part, format string, args []interface{}) {
ms.add(obj, part, fmt.Sprintf(format, args...))
}
func (d *differ) checkPackage() {
// Old changes.
for _, name := range d.old.Scope().Names() {
oldobj := d.old.Scope().Lookup(name)
if !oldobj.Exported() {
continue
}
newobj := d.new.Scope().Lookup(name)
if newobj == nil {
d.incompatible(oldobj, "", "removed")
continue
}
d.checkObjects(oldobj, newobj)
}
// New additions.
for _, name := range d.new.Scope().Names() {
newobj := d.new.Scope().Lookup(name)
if newobj.Exported() && d.old.Scope().Lookup(name) == nil {
d.compatible(newobj, "", "added")
}
}
// Whole-package satisfaction.
// For every old exposed interface oIface and its corresponding new interface nIface...
for otn1, nt1 := range d.correspondMap {
oIface, ok := otn1.Type().Underlying().(*types.Interface)
if !ok {
continue
}
nIface, ok := nt1.Underlying().(*types.Interface)
if !ok {
// If nt1 isn't an interface but otn1 is, then that's an incompatibility that
// we've already noticed, so there's no need to do anything here.
continue
}
// For every old type that implements oIface, its corresponding new type must implement
// nIface.
for otn2, nt2 := range d.correspondMap {
if otn1 == otn2 {
continue
}
if types.Implements(otn2.Type(), oIface) && !types.Implements(nt2, nIface) {
d.incompatible(otn2, "", "no longer implements %s", objectString(otn1))
}
}
}
}
func (d *differ) checkObjects(old, new types.Object) {
switch old := old.(type) {
case *types.Const:
if new, ok := new.(*types.Const); ok {
d.constChanges(old, new)
return
}
case *types.Var:
if new, ok := new.(*types.Var); ok {
d.checkCorrespondence(old, "", old.Type(), new.Type())
return
}
case *types.Func:
switch new := new.(type) {
case *types.Func:
d.checkCorrespondence(old, "", old.Type(), new.Type())
return
case *types.Var:
d.compatible(old, "", "changed from func to var")
d.checkCorrespondence(old, "", old.Type(), new.Type())
return
}
case *types.TypeName:
if new, ok := new.(*types.TypeName); ok {
d.checkCorrespondence(old, "", old.Type(), new.Type())
return
}
default:
panic("unexpected obj type")
}
// Here if kind of type changed.
d.incompatible(old, "", "changed from %s to %s",
objectKindString(old), objectKindString(new))
}
// Compare two constants.
func (d *differ) constChanges(old, new *types.Const) {
ot := old.Type()
nt := new.Type()
// Check for change of type.
if !d.correspond(ot, nt) {
d.typeChanged(old, "", ot, nt)
return
}
// Check for change of value.
// We know the types are the same, so constant.Compare shouldn't panic.
if !constant.Compare(old.Val(), token.EQL, new.Val()) {
d.incompatible(old, "", "value changed from %s to %s", old.Val(), new.Val())
}
}
func objectKindString(obj types.Object) string {
switch obj.(type) {
case *types.Const:
return "const"
case *types.Var:
return "var"
case *types.Func:
return "func"
case *types.TypeName:
return "type"
default:
return "???"
}
}
func (d *differ) checkCorrespondence(obj types.Object, part string, old, new types.Type) {
if !d.correspond(old, new) {
d.typeChanged(obj, part, old, new)
}
}
func (d *differ) typeChanged(obj types.Object, part string, old, new types.Type) {
old = removeNamesFromSignature(old)
new = removeNamesFromSignature(new)
olds := types.TypeString(old, types.RelativeTo(d.old))
news := types.TypeString(new, types.RelativeTo(d.new))
d.incompatible(obj, part, "changed from %s to %s", olds, news)
}
// go/types always includes the argument and result names when formatting a signature.
// Since these can change without affecting compatibility, we don't want users to
// be distracted by them, so we remove them.
func removeNamesFromSignature(t types.Type) types.Type {
t = aliases.Unalias(t)
sig, ok := t.(*types.Signature)
if !ok {
return t
}
dename := func(p *types.Tuple) *types.Tuple {
var vars []*types.Var
for i := 0; i < p.Len(); i++ {
v := p.At(i)
vars = append(vars, types.NewVar(v.Pos(), v.Pkg(), "", aliases.Unalias(v.Type())))
}
return types.NewTuple(vars...)
}
return types.NewSignature(sig.Recv(), dename(sig.Params()), dename(sig.Results()), sig.Variadic())
}
| tools/internal/apidiff/apidiff.go/0 | {
"file_path": "tools/internal/apidiff/apidiff.go",
"repo_id": "tools",
"token_count": 2497
} | 759 |
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package lcs
import (
"log"
"sort"
)
// lcs is a longest common sequence
type lcs []diag
// A diag is a piece of the edit graph where A[X+i] == B[Y+i], for 0<=i<Len.
// All computed diagonals are parts of a longest common subsequence.
type diag struct {
X, Y int
Len int
}
// sort sorts in place, by lowest X, and if tied, inversely by Len
func (l lcs) sort() lcs {
sort.Slice(l, func(i, j int) bool {
if l[i].X != l[j].X {
return l[i].X < l[j].X
}
return l[i].Len > l[j].Len
})
return l
}
// validate that the elements of the lcs do not overlap
// (can only happen when the two-sided algorithm ends early)
// expects the lcs to be sorted
func (l lcs) valid() bool {
for i := 1; i < len(l); i++ {
if l[i-1].X+l[i-1].Len > l[i].X {
return false
}
if l[i-1].Y+l[i-1].Len > l[i].Y {
return false
}
}
return true
}
// repair overlapping lcs
// only called if two-sided stops early
func (l lcs) fix() lcs {
// from the set of diagonals in l, find a maximal non-conflicting set
// this problem may be NP-complete, but we use a greedy heuristic,
// which is quadratic, but with a better data structure, could be D log D.
// indepedent is not enough: {0,3,1} and {3,0,2} can't both occur in an lcs
// which has to have monotone x and y
if len(l) == 0 {
return nil
}
sort.Slice(l, func(i, j int) bool { return l[i].Len > l[j].Len })
tmp := make(lcs, 0, len(l))
tmp = append(tmp, l[0])
for i := 1; i < len(l); i++ {
var dir direction
nxt := l[i]
for _, in := range tmp {
if dir, nxt = overlap(in, nxt); dir == empty || dir == bad {
break
}
}
if nxt.Len > 0 && dir != bad {
tmp = append(tmp, nxt)
}
}
tmp.sort()
if false && !tmp.valid() { // debug checking
log.Fatalf("here %d", len(tmp))
}
return tmp
}
type direction int
const (
empty direction = iota // diag is empty (so not in lcs)
leftdown // proposed acceptably to the left and below
rightup // proposed diag is acceptably to the right and above
bad // proposed diag is inconsistent with the lcs so far
)
// overlap trims the proposed diag prop so it doesn't overlap with
// the existing diag that has already been added to the lcs.
func overlap(exist, prop diag) (direction, diag) {
if prop.X <= exist.X && exist.X < prop.X+prop.Len {
// remove the end of prop where it overlaps with the X end of exist
delta := prop.X + prop.Len - exist.X
prop.Len -= delta
if prop.Len <= 0 {
return empty, prop
}
}
if exist.X <= prop.X && prop.X < exist.X+exist.Len {
// remove the beginning of prop where overlaps with exist
delta := exist.X + exist.Len - prop.X
prop.Len -= delta
if prop.Len <= 0 {
return empty, prop
}
prop.X += delta
prop.Y += delta
}
if prop.Y <= exist.Y && exist.Y < prop.Y+prop.Len {
// remove the end of prop that overlaps (in Y) with exist
delta := prop.Y + prop.Len - exist.Y
prop.Len -= delta
if prop.Len <= 0 {
return empty, prop
}
}
if exist.Y <= prop.Y && prop.Y < exist.Y+exist.Len {
// remove the beginning of peop that overlaps with exist
delta := exist.Y + exist.Len - prop.Y
prop.Len -= delta
if prop.Len <= 0 {
return empty, prop
}
prop.X += delta // no test reaches this code
prop.Y += delta
}
if prop.X+prop.Len <= exist.X && prop.Y+prop.Len <= exist.Y {
return leftdown, prop
}
if exist.X+exist.Len <= prop.X && exist.Y+exist.Len <= prop.Y {
return rightup, prop
}
// prop can't be in an lcs that contains exist
return bad, prop
}
// manipulating Diag and lcs
// prepend a diagonal (x,y)-(x+1,y+1) segment either to an empty lcs
// or to its first Diag. prepend is only called to extend diagonals
// the backward direction.
func (lcs lcs) prepend(x, y int) lcs {
if len(lcs) > 0 {
d := &lcs[0]
if int(d.X) == x+1 && int(d.Y) == y+1 {
// extend the diagonal down and to the left
d.X, d.Y = int(x), int(y)
d.Len++
return lcs
}
}
r := diag{X: int(x), Y: int(y), Len: 1}
lcs = append([]diag{r}, lcs...)
return lcs
}
// append appends a diagonal, or extends the existing one.
// by adding the edge (x,y)-(x+1.y+1). append is only called
// to extend diagonals in the forward direction.
func (lcs lcs) append(x, y int) lcs {
if len(lcs) > 0 {
last := &lcs[len(lcs)-1]
// Expand last element if adjoining.
if last.X+last.Len == x && last.Y+last.Len == y {
last.Len++
return lcs
}
}
return append(lcs, diag{X: x, Y: y, Len: 1})
}
// enforce constraint on d, k
func ok(d, k int) bool {
return d >= 0 && -d <= k && k <= d
}
| tools/internal/diff/lcs/common.go/0 | {
"file_path": "tools/internal/diff/lcs/common.go",
"repo_id": "tools",
"token_count": 1905
} | 760 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package core
import (
"context"
"sync/atomic"
"time"
"unsafe"
"golang.org/x/tools/internal/event/label"
)
// Exporter is a function that handles events.
// It may return a modified context and event.
type Exporter func(context.Context, Event, label.Map) context.Context
var (
exporter unsafe.Pointer
)
// SetExporter sets the global exporter function that handles all events.
// The exporter is called synchronously from the event call site, so it should
// return quickly so as not to hold up user code.
func SetExporter(e Exporter) {
p := unsafe.Pointer(&e)
if e == nil {
// &e is always valid, and so p is always valid, but for the early abort
// of ProcessEvent to be efficient it needs to make the nil check on the
// pointer without having to dereference it, so we make the nil function
// also a nil pointer
p = nil
}
atomic.StorePointer(&exporter, p)
}
// deliver is called to deliver an event to the supplied exporter.
// it will fill in the time.
func deliver(ctx context.Context, exporter Exporter, ev Event) context.Context {
// add the current time to the event
ev.at = time.Now()
// hand the event off to the current exporter
return exporter(ctx, ev, ev)
}
// Export is called to deliver an event to the global exporter if set.
func Export(ctx context.Context, ev Event) context.Context {
// get the global exporter and abort early if there is not one
exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter))
if exporterPtr == nil {
return ctx
}
return deliver(ctx, *exporterPtr, ev)
}
// ExportPair is called to deliver a start event to the supplied exporter.
// It also returns a function that will deliver the end event to the same
// exporter.
// It will fill in the time.
func ExportPair(ctx context.Context, begin, end Event) (context.Context, func()) {
// get the global exporter and abort early if there is not one
exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter))
if exporterPtr == nil {
return ctx, func() {}
}
ctx = deliver(ctx, *exporterPtr, begin)
return ctx, func() { deliver(ctx, *exporterPtr, end) }
}
| tools/internal/event/core/export.go/0 | {
"file_path": "tools/internal/event/core/export.go",
"repo_id": "tools",
"token_count": 679
} | 761 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ocagent_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"testing"
"time"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/event/core"
"golang.org/x/tools/internal/event/export"
"golang.org/x/tools/internal/event/export/metric"
"golang.org/x/tools/internal/event/export/ocagent"
"golang.org/x/tools/internal/event/keys"
"golang.org/x/tools/internal/event/label"
)
const testNodeStr = `{
"node":{
"identifier":{
"host_name":"tester",
"pid":1,
"start_timestamp":"1970-01-01T00:00:00Z"
},
"library_info":{
"language":4,
"exporter_version":"0.0.1",
"core_library_version":"x/tools"
},
"service_info":{
"name":"ocagent-tests"
}
},`
var (
keyDB = keys.NewString("db", "the database name")
keyMethod = keys.NewString("method", "a metric grouping key")
keyRoute = keys.NewString("route", "another metric grouping key")
key1DB = keys.NewString("1_db", "A test string key")
key2aAge = keys.NewFloat64("2a_age", "A test float64 key")
key2bTTL = keys.NewFloat32("2b_ttl", "A test float32 key")
key2cExpiryMS = keys.NewFloat64("2c_expiry_ms", "A test float64 key")
key3aRetry = keys.NewBoolean("3a_retry", "A test boolean key")
key3bStale = keys.NewBoolean("3b_stale", "Another test boolean key")
key4aMax = keys.NewInt("4a_max", "A test int key")
key4bOpcode = keys.NewInt8("4b_opcode", "A test int8 key")
key4cBase = keys.NewInt16("4c_base", "A test int16 key")
key4eChecksum = keys.NewInt32("4e_checksum", "A test int32 key")
key4fMode = keys.NewInt64("4f_mode", "A test int64 key")
key5aMin = keys.NewUInt("5a_min", "A test uint key")
key5bMix = keys.NewUInt8("5b_mix", "A test uint8 key")
key5cPort = keys.NewUInt16("5c_port", "A test uint16 key")
key5dMinHops = keys.NewUInt32("5d_min_hops", "A test uint32 key")
key5eMaxHops = keys.NewUInt64("5e_max_hops", "A test uint64 key")
recursiveCalls = keys.NewInt64("recursive_calls", "Number of recursive calls")
bytesIn = keys.NewInt64("bytes_in", "Number of bytes in") //, unit.Bytes)
latencyMs = keys.NewFloat64("latency", "The latency in milliseconds") //, unit.Milliseconds)
metricLatency = metric.HistogramFloat64{
Name: "latency_ms",
Description: "The latency of calls in milliseconds",
Keys: []label.Key{keyMethod, keyRoute},
Buckets: []float64{0, 5, 10, 25, 50},
}
metricBytesIn = metric.HistogramInt64{
Name: "latency_ms",
Description: "The latency of calls in milliseconds",
Keys: []label.Key{keyMethod, keyRoute},
Buckets: []int64{0, 10, 50, 100, 500, 1000, 2000},
}
metricRecursiveCalls = metric.Scalar{
Name: "latency_ms",
Description: "The latency of calls in milliseconds",
Keys: []label.Key{keyMethod, keyRoute},
}
)
type testExporter struct {
ocagent *ocagent.Exporter
sent fakeSender
}
func registerExporter() *testExporter {
exporter := &testExporter{}
cfg := ocagent.Config{
Host: "tester",
Process: 1,
Service: "ocagent-tests",
Client: &http.Client{Transport: &exporter.sent},
}
cfg.Start, _ = time.Parse(time.RFC3339Nano, "1970-01-01T00:00:00Z")
exporter.ocagent = ocagent.Connect(&cfg)
metrics := metric.Config{}
metricLatency.Record(&metrics, latencyMs)
metricBytesIn.Record(&metrics, bytesIn)
metricRecursiveCalls.SumInt64(&metrics, recursiveCalls)
e := exporter.ocagent.ProcessEvent
e = metrics.Exporter(e)
e = spanFixer(e)
e = export.Spans(e)
e = export.Labels(e)
e = timeFixer(e)
event.SetExporter(e)
return exporter
}
func timeFixer(output event.Exporter) event.Exporter {
start, _ := time.Parse(time.RFC3339Nano, "1970-01-01T00:00:30Z")
at, _ := time.Parse(time.RFC3339Nano, "1970-01-01T00:00:40Z")
end, _ := time.Parse(time.RFC3339Nano, "1970-01-01T00:00:50Z")
return func(ctx context.Context, ev core.Event, lm label.Map) context.Context {
switch {
case event.IsStart(ev):
ev = core.CloneEvent(ev, start)
case event.IsEnd(ev):
ev = core.CloneEvent(ev, end)
default:
ev = core.CloneEvent(ev, at)
}
return output(ctx, ev, lm)
}
}
func spanFixer(output event.Exporter) event.Exporter {
return func(ctx context.Context, ev core.Event, lm label.Map) context.Context {
if event.IsStart(ev) {
span := export.GetSpan(ctx)
span.ID = export.SpanContext{}
}
return output(ctx, ev, lm)
}
}
func (e *testExporter) Output(route string) []byte {
e.ocagent.Flush()
return e.sent.get(route)
}
func checkJSON(t *testing.T, got, want []byte) {
// compare the compact form, to allow for formatting differences
g := &bytes.Buffer{}
if err := json.Compact(g, got); err != nil {
t.Fatal(err)
}
w := &bytes.Buffer{}
if err := json.Compact(w, want); err != nil {
t.Fatal(err)
}
if g.String() != w.String() {
t.Fatalf("Got:\n%s\nWant:\n%s", g, w)
}
}
type fakeSender struct {
mu sync.Mutex
data map[string][]byte
}
func (s *fakeSender) get(route string) []byte {
s.mu.Lock()
defer s.mu.Unlock()
data, found := s.data[route]
if found {
delete(s.data, route)
}
return data
}
func (s *fakeSender) RoundTrip(req *http.Request) (*http.Response, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.data == nil {
s.data = make(map[string][]byte)
}
data, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
path := req.URL.EscapedPath()
if _, found := s.data[path]; found {
return nil, fmt.Errorf("duplicate delivery to %v", path)
}
s.data[path] = data
return &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
}, nil
}
| tools/internal/event/export/ocagent/ocagent_test.go/0 | {
"file_path": "tools/internal/event/export/ocagent/ocagent_test.go",
"repo_id": "tools",
"token_count": 2484
} | 762 |
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !go1.11
// +build !go1.11
package gcimporter
import "go/types"
func newInterface(methods []*types.Func, embeddeds []types.Type) *types.Interface {
named := make([]*types.Named, len(embeddeds))
for i, e := range embeddeds {
var ok bool
named[i], ok = e.(*types.Named)
if !ok {
panic("embedding of non-defined interfaces in interfaces is not supported before Go 1.11")
}
}
return types.NewInterface(methods, named)
}
| tools/internal/gcimporter/newInterface10.go/0 | {
"file_path": "tools/internal/gcimporter/newInterface10.go",
"repo_id": "tools",
"token_count": 210
} | 763 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gocommand
import (
"context"
"fmt"
"regexp"
"strings"
)
// GoVersion reports the minor version number of the highest release
// tag built into the go command on the PATH.
//
// Note that this may be higher than the version of the go tool used
// to build this application, and thus the versions of the standard
// go/{scanner,parser,ast,types} packages that are linked into it.
// In that case, callers should either downgrade to the version of
// go used to build the application, or report an error that the
// application is too old to use the go command on the PATH.
func GoVersion(ctx context.Context, inv Invocation, r *Runner) (int, error) {
inv.Verb = "list"
inv.Args = []string{"-e", "-f", `{{context.ReleaseTags}}`, `--`, `unsafe`}
inv.BuildFlags = nil // This is not a build command.
inv.ModFlag = ""
inv.ModFile = ""
inv.Env = append(inv.Env[:len(inv.Env):len(inv.Env)], "GO111MODULE=off")
stdoutBytes, err := r.Run(ctx, inv)
if err != nil {
return 0, err
}
stdout := stdoutBytes.String()
if len(stdout) < 3 {
return 0, fmt.Errorf("bad ReleaseTags output: %q", stdout)
}
// Split up "[go1.1 go1.15]" and return highest go1.X value.
tags := strings.Fields(stdout[1 : len(stdout)-2])
for i := len(tags) - 1; i >= 0; i-- {
var version int
if _, err := fmt.Sscanf(tags[i], "go1.%d", &version); err != nil {
continue
}
return version, nil
}
return 0, fmt.Errorf("no parseable ReleaseTags in %v", tags)
}
// GoVersionOutput returns the complete output of the go version command.
func GoVersionOutput(ctx context.Context, inv Invocation, r *Runner) (string, error) {
inv.Verb = "version"
goVersion, err := r.Run(ctx, inv)
if err != nil {
return "", err
}
return goVersion.String(), nil
}
// ParseGoVersionOutput extracts the Go version string
// from the output of the "go version" command.
// Given an unrecognized form, it returns an empty string.
func ParseGoVersionOutput(data string) string {
re := regexp.MustCompile(`^go version (go\S+|devel \S+)`)
m := re.FindStringSubmatch(data)
if len(m) != 2 {
return "" // unrecognized version
}
return m[1]
}
| tools/internal/gocommand/version.go/0 | {
"file_path": "tools/internal/gocommand/version.go",
"repo_id": "tools",
"token_count": 778
} | 764 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonrpc2
import (
"context"
"errors"
"io"
"math"
"net"
"os"
"time"
"golang.org/x/tools/internal/event"
)
// NOTE: This file provides an experimental API for serving multiple remote
// jsonrpc2 clients over the network. For now, it is intentionally similar to
// net/http, but that may change in the future as we figure out the correct
// semantics.
// A StreamServer is used to serve incoming jsonrpc2 clients communicating over
// a newly created connection.
type StreamServer interface {
ServeStream(context.Context, Conn) error
}
// The ServerFunc type is an adapter that implements the StreamServer interface
// using an ordinary function.
type ServerFunc func(context.Context, Conn) error
// ServeStream calls f(ctx, s).
func (f ServerFunc) ServeStream(ctx context.Context, c Conn) error {
return f(ctx, c)
}
// HandlerServer returns a StreamServer that handles incoming streams using the
// provided handler.
func HandlerServer(h Handler) StreamServer {
return ServerFunc(func(ctx context.Context, conn Conn) error {
conn.Go(ctx, h)
<-conn.Done()
return conn.Err()
})
}
// ListenAndServe starts an jsonrpc2 server on the given address. If
// idleTimeout is non-zero, ListenAndServe exits after there are no clients for
// this duration, otherwise it exits only on error.
func ListenAndServe(ctx context.Context, network, addr string, server StreamServer, idleTimeout time.Duration) error {
ln, err := net.Listen(network, addr)
if err != nil {
return err
}
defer ln.Close()
if network == "unix" {
defer os.Remove(addr)
}
return Serve(ctx, ln, server, idleTimeout)
}
// Serve accepts incoming connections from the network, and handles them using
// the provided server. If idleTimeout is non-zero, ListenAndServe exits after
// there are no clients for this duration, otherwise it exits only on error.
func Serve(ctx context.Context, ln net.Listener, server StreamServer, idleTimeout time.Duration) error {
newConns := make(chan net.Conn)
closedConns := make(chan error)
activeConns := 0
var acceptErr error
go func() {
defer close(newConns)
for {
var nc net.Conn
nc, acceptErr = ln.Accept()
if acceptErr != nil {
return
}
newConns <- nc
}
}()
ctx, cancel := context.WithCancel(ctx)
defer func() {
// Signal the Accept goroutine to stop immediately
// and terminate all newly-accepted connections until it returns.
ln.Close()
for nc := range newConns {
nc.Close()
}
// Cancel pending ServeStream callbacks and wait for them to finish.
cancel()
for activeConns > 0 {
err := <-closedConns
if !isClosingError(err) {
event.Error(ctx, "closed a connection", err)
}
activeConns--
}
}()
// Max duration: ~290 years; surely that's long enough.
const forever = math.MaxInt64
if idleTimeout <= 0 {
idleTimeout = forever
}
connTimer := time.NewTimer(idleTimeout)
defer connTimer.Stop()
for {
select {
case netConn, ok := <-newConns:
if !ok {
return acceptErr
}
if activeConns == 0 && !connTimer.Stop() {
// connTimer.C may receive a value even after Stop returns.
// (See https://golang.org/issue/37196.)
<-connTimer.C
}
activeConns++
stream := NewHeaderStream(netConn)
go func() {
conn := NewConn(stream)
err := server.ServeStream(ctx, conn)
stream.Close()
closedConns <- err
}()
case err := <-closedConns:
if !isClosingError(err) {
event.Error(ctx, "closed a connection", err)
}
activeConns--
if activeConns == 0 {
connTimer.Reset(idleTimeout)
}
case <-connTimer.C:
return ErrIdleTimeout
case <-ctx.Done():
return nil
}
}
}
// isClosingError reports if the error occurs normally during the process of
// closing a network connection. It uses imperfect heuristics that err on the
// side of false negatives, and should not be used for anything critical.
func isClosingError(err error) bool {
if errors.Is(err, io.EOF) {
return true
}
// Per https://github.com/golang/go/issues/4373, this error string should not
// change. This is not ideal, but since the worst that could happen here is
// some superfluous logging, it is acceptable.
if err.Error() == "use of closed network connection" {
return true
}
return false
}
| tools/internal/jsonrpc2/serve.go/0 | {
"file_path": "tools/internal/jsonrpc2/serve.go",
"repo_id": "tools",
"token_count": 1487
} | 765 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jsonrpc2_test
import (
"context"
"errors"
"fmt"
"runtime/debug"
"testing"
"time"
jsonrpc2 "golang.org/x/tools/internal/jsonrpc2_v2"
"golang.org/x/tools/internal/stack/stacktest"
"golang.org/x/tools/internal/testenv"
)
func TestIdleTimeout(t *testing.T) {
testenv.NeedsLocalhostNet(t)
stacktest.NoLeak(t)
// Use a panicking time.AfterFunc instead of context.WithTimeout so that we
// get a goroutine dump on failure. We expect the test to take on the order of
// a few tens of milliseconds at most, so 10s should be several orders of
// magnitude of headroom.
timer := time.AfterFunc(10*time.Second, func() {
debug.SetTraceback("all")
panic("TestIdleTimeout deadlocked")
})
defer timer.Stop()
ctx := context.Background()
try := func(d time.Duration) (longEnough bool) {
listener, err := jsonrpc2.NetListener(ctx, "tcp", "localhost:0", jsonrpc2.NetListenOptions{})
if err != nil {
t.Fatal(err)
}
idleStart := time.Now()
listener = jsonrpc2.NewIdleListener(d, listener)
defer listener.Close()
server := jsonrpc2.NewServer(ctx, listener, jsonrpc2.ConnectionOptions{})
// Exercise some connection/disconnection patterns, and then assert that when
// our timer fires, the server exits.
conn1, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{})
if err != nil {
if since := time.Since(idleStart); since < d {
t.Fatalf("conn1 failed to connect after %v: %v", since, err)
}
t.Log("jsonrpc2.Dial:", err)
return false // Took to long to dial, so the failure could have been due to the idle timeout.
}
// On the server side, Accept can race with the connection timing out.
// Send a call and wait for the response to ensure that the connection was
// actually fully accepted.
ac := conn1.Call(ctx, "ping", nil)
if err := ac.Await(ctx, nil); !errors.Is(err, jsonrpc2.ErrMethodNotFound) {
if since := time.Since(idleStart); since < d {
t.Fatalf("conn1 broken after %v: %v", since, err)
}
t.Log(`conn1.Call(ctx, "ping", nil):`, err)
conn1.Close()
return false
}
// Since conn1 was successfully accepted and remains open, the server is
// definitely non-idle. Dialing another simultaneous connection should
// succeed.
conn2, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{})
if err != nil {
conn1.Close()
t.Fatalf("conn2 failed to connect while non-idle after %v: %v", time.Since(idleStart), err)
return false
}
// Ensure that conn2 is also accepted on the server side before we close
// conn1. Otherwise, the connection can appear idle if the server processes
// the closure of conn1 and the idle timeout before it finally notices conn2
// in the accept queue.
// (That failure mode may explain the failure noted in
// https://go.dev/issue/49387#issuecomment-1303979877.)
ac = conn2.Call(ctx, "ping", nil)
if err := ac.Await(ctx, nil); !errors.Is(err, jsonrpc2.ErrMethodNotFound) {
t.Fatalf("conn2 broken while non-idle after %v: %v", time.Since(idleStart), err)
}
if err := conn1.Close(); err != nil {
t.Fatalf("conn1.Close failed with error: %v", err)
}
idleStart = time.Now()
if err := conn2.Close(); err != nil {
t.Fatalf("conn2.Close failed with error: %v", err)
}
conn3, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{})
if err != nil {
if since := time.Since(idleStart); since < d {
t.Fatalf("conn3 failed to connect after %v: %v", since, err)
}
t.Log("jsonrpc2.Dial:", err)
return false // Took to long to dial, so the failure could have been due to the idle timeout.
}
ac = conn3.Call(ctx, "ping", nil)
if err := ac.Await(ctx, nil); !errors.Is(err, jsonrpc2.ErrMethodNotFound) {
if since := time.Since(idleStart); since < d {
t.Fatalf("conn3 broken after %v: %v", since, err)
}
t.Log(`conn3.Call(ctx, "ping", nil):`, err)
conn3.Close()
return false
}
idleStart = time.Now()
if err := conn3.Close(); err != nil {
t.Fatalf("conn3.Close failed with error: %v", err)
}
serverError := server.Wait()
if !errors.Is(serverError, jsonrpc2.ErrIdleTimeout) {
t.Errorf("run() returned error %v, want %v", serverError, jsonrpc2.ErrIdleTimeout)
}
if since := time.Since(idleStart); since < d {
t.Errorf("server shut down after %v idle; want at least %v", since, d)
}
return true
}
d := 1 * time.Millisecond
for {
t.Logf("testing with idle timeout %v", d)
if !try(d) {
d *= 2
continue
}
break
}
}
type msg struct {
Msg string
}
type fakeHandler struct{}
func (fakeHandler) Handle(ctx context.Context, req *jsonrpc2.Request) (interface{}, error) {
switch req.Method {
case "ping":
return &msg{"pong"}, nil
default:
return nil, jsonrpc2.ErrNotHandled
}
}
func TestServe(t *testing.T) {
stacktest.NoLeak(t)
ctx := context.Background()
tests := []struct {
name string
factory func(context.Context, testing.TB) (jsonrpc2.Listener, error)
}{
{"tcp", func(ctx context.Context, t testing.TB) (jsonrpc2.Listener, error) {
testenv.NeedsLocalhostNet(t)
return jsonrpc2.NetListener(ctx, "tcp", "localhost:0", jsonrpc2.NetListenOptions{})
}},
{"pipe", func(ctx context.Context, t testing.TB) (jsonrpc2.Listener, error) {
return jsonrpc2.NetPipeListener(ctx)
}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fake, err := test.factory(ctx, t)
if err != nil {
t.Fatal(err)
}
conn, shutdown, err := newFake(t, ctx, fake)
if err != nil {
t.Fatal(err)
}
defer shutdown()
var got msg
if err := conn.Call(ctx, "ping", &msg{"ting"}).Await(ctx, &got); err != nil {
t.Fatal(err)
}
if want := "pong"; got.Msg != want {
t.Errorf("conn.Call(...): returned %q, want %q", got, want)
}
})
}
}
func newFake(t *testing.T, ctx context.Context, l jsonrpc2.Listener) (*jsonrpc2.Connection, func(), error) {
server := jsonrpc2.NewServer(ctx, l, jsonrpc2.ConnectionOptions{
Handler: fakeHandler{},
})
client, err := jsonrpc2.Dial(ctx,
l.Dialer(),
jsonrpc2.ConnectionOptions{
Handler: fakeHandler{},
})
if err != nil {
return nil, nil, err
}
return client, func() {
if err := l.Close(); err != nil {
t.Fatal(err)
}
if err := client.Close(); err != nil {
t.Fatal(err)
}
server.Wait()
}, nil
}
// TestIdleListenerAcceptCloseRace checks for the Accept/Close race fixed in CL 388597.
//
// (A bug in the idleListener implementation caused a successful Accept to block
// on sending to a background goroutine that could have already exited.)
func TestIdleListenerAcceptCloseRace(t *testing.T) {
ctx := context.Background()
n := 10
// Each iteration of the loop appears to take around a millisecond, so to
// avoid spurious failures we'll set the watchdog for three orders of
// magnitude longer. When the bug was present, this reproduced the deadlock
// reliably on a Linux workstation when run with -count=100, which should be
// frequent enough to show up on the Go build dashboard if it regresses.
watchdog := time.Duration(n) * 1000 * time.Millisecond
timer := time.AfterFunc(watchdog, func() {
debug.SetTraceback("all")
panic(fmt.Sprintf("%s deadlocked after %v", t.Name(), watchdog))
})
defer timer.Stop()
for ; n > 0; n-- {
listener, err := jsonrpc2.NetPipeListener(ctx)
if err != nil {
t.Fatal(err)
}
listener = jsonrpc2.NewIdleListener(24*time.Hour, listener)
done := make(chan struct{})
go func() {
conn, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{})
listener.Close()
if err == nil {
conn.Close()
}
close(done)
}()
// Accept may return a non-nil error if Close closes the underlying network
// connection before the wrapped Accept call unblocks. However, it must not
// deadlock!
c, err := listener.Accept(ctx)
if err == nil {
c.Close()
}
<-done
}
}
// TestCloseCallRace checks for a race resulting in a deadlock when a Call on
// one side of the connection races with a Close (or otherwise broken
// connection) initiated from the other side.
//
// (The Call method was waiting for a result from the Read goroutine to
// determine which error value to return, but the Read goroutine was waiting for
// in-flight calls to complete before reporting that result.)
func TestCloseCallRace(t *testing.T) {
ctx := context.Background()
n := 10
watchdog := time.Duration(n) * 1000 * time.Millisecond
timer := time.AfterFunc(watchdog, func() {
debug.SetTraceback("all")
panic(fmt.Sprintf("%s deadlocked after %v", t.Name(), watchdog))
})
defer timer.Stop()
for ; n > 0; n-- {
listener, err := jsonrpc2.NetPipeListener(ctx)
if err != nil {
t.Fatal(err)
}
pokec := make(chan *jsonrpc2.AsyncCall, 1)
s := jsonrpc2.NewServer(ctx, listener, jsonrpc2.BinderFunc(func(_ context.Context, srvConn *jsonrpc2.Connection) jsonrpc2.ConnectionOptions {
h := jsonrpc2.HandlerFunc(func(ctx context.Context, _ *jsonrpc2.Request) (interface{}, error) {
// Start a concurrent call from the server to the client.
// The point of this test is to ensure this doesn't deadlock
// if the client shuts down the connection concurrently.
//
// The racing Call may or may not receive a response: it should get a
// response if it is sent before the client closes the connection, and
// it should fail with some kind of "connection closed" error otherwise.
go func() {
pokec <- srvConn.Call(ctx, "poke", nil)
}()
return &msg{"pong"}, nil
})
return jsonrpc2.ConnectionOptions{Handler: h}
}))
dialConn, err := jsonrpc2.Dial(ctx, listener.Dialer(), jsonrpc2.ConnectionOptions{})
if err != nil {
listener.Close()
s.Wait()
t.Fatal(err)
}
// Calling any method on the server should provoke it to asynchronously call
// us back. While it is starting that call, we will close the connection.
if err := dialConn.Call(ctx, "ping", nil).Await(ctx, nil); err != nil {
t.Error(err)
}
if err := dialConn.Close(); err != nil {
t.Error(err)
}
// Ensure that the Call on the server side did not block forever when the
// connection closed.
pokeCall := <-pokec
if err := pokeCall.Await(ctx, nil); err == nil {
t.Errorf("unexpected nil error from server-initited call")
} else if errors.Is(err, jsonrpc2.ErrMethodNotFound) {
// The call completed before the Close reached the handler.
} else {
// The error was something else.
t.Logf("server-initiated call completed with expected error: %v", err)
}
listener.Close()
s.Wait()
}
}
| tools/internal/jsonrpc2_v2/serve_test.go/0 | {
"file_path": "tools/internal/jsonrpc2_v2/serve_test.go",
"repo_id": "tools",
"token_count": 3979
} | 766 |
// Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT.
package pkgbits
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[SyncEOF-1]
_ = x[SyncBool-2]
_ = x[SyncInt64-3]
_ = x[SyncUint64-4]
_ = x[SyncString-5]
_ = x[SyncValue-6]
_ = x[SyncVal-7]
_ = x[SyncRelocs-8]
_ = x[SyncReloc-9]
_ = x[SyncUseReloc-10]
_ = x[SyncPublic-11]
_ = x[SyncPos-12]
_ = x[SyncPosBase-13]
_ = x[SyncObject-14]
_ = x[SyncObject1-15]
_ = x[SyncPkg-16]
_ = x[SyncPkgDef-17]
_ = x[SyncMethod-18]
_ = x[SyncType-19]
_ = x[SyncTypeIdx-20]
_ = x[SyncTypeParamNames-21]
_ = x[SyncSignature-22]
_ = x[SyncParams-23]
_ = x[SyncParam-24]
_ = x[SyncCodeObj-25]
_ = x[SyncSym-26]
_ = x[SyncLocalIdent-27]
_ = x[SyncSelector-28]
_ = x[SyncPrivate-29]
_ = x[SyncFuncExt-30]
_ = x[SyncVarExt-31]
_ = x[SyncTypeExt-32]
_ = x[SyncPragma-33]
_ = x[SyncExprList-34]
_ = x[SyncExprs-35]
_ = x[SyncExpr-36]
_ = x[SyncExprType-37]
_ = x[SyncAssign-38]
_ = x[SyncOp-39]
_ = x[SyncFuncLit-40]
_ = x[SyncCompLit-41]
_ = x[SyncDecl-42]
_ = x[SyncFuncBody-43]
_ = x[SyncOpenScope-44]
_ = x[SyncCloseScope-45]
_ = x[SyncCloseAnotherScope-46]
_ = x[SyncDeclNames-47]
_ = x[SyncDeclName-48]
_ = x[SyncStmts-49]
_ = x[SyncBlockStmt-50]
_ = x[SyncIfStmt-51]
_ = x[SyncForStmt-52]
_ = x[SyncSwitchStmt-53]
_ = x[SyncRangeStmt-54]
_ = x[SyncCaseClause-55]
_ = x[SyncCommClause-56]
_ = x[SyncSelectStmt-57]
_ = x[SyncDecls-58]
_ = x[SyncLabeledStmt-59]
_ = x[SyncUseObjLocal-60]
_ = x[SyncAddLocal-61]
_ = x[SyncLinkname-62]
_ = x[SyncStmt1-63]
_ = x[SyncStmtsEnd-64]
_ = x[SyncLabel-65]
_ = x[SyncOptLabel-66]
}
const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabel"
var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458}
func (i SyncMarker) String() string {
i -= 1
if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) {
return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")"
}
return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]]
}
| tools/internal/pkgbits/syncmarker_string.go/0 | {
"file_path": "tools/internal/pkgbits/syncmarker_string.go",
"repo_id": "tools",
"token_count": 1314
} | 767 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package inline_test
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"testing"
"golang.org/x/tools/internal/refactor/inline"
)
// TestCalleeEffects is a unit test of the calleefx analysis.
func TestCalleeEffects(t *testing.T) {
// Each callee must declare a function or method named f.
const funcName = "f"
var tests = []struct {
descr string
callee string // Go source file (sans package decl) containing callee decl
want string // expected effects string (-1=R∞ -2=W∞)
}{
{
"Assignments have unknown effects.",
`func f(x, y int) { x = y }`,
`[0 1 -2]`,
},
{
"Reads from globals are impure.",
`func f() { _ = g }; var g int`,
`[-1]`,
},
{
"Writes to globals have effects.",
`func f() { g = 0 }; var g int`,
`[-1 -2]`, // the -1 is spurious but benign
},
{
"Blank assign has no effect.",
`func f(x int) { _ = x }`,
`[0]`,
},
{
"Short decl of new var has has no effect.",
`func f(x int) { y := x; _ = y }`,
`[0]`,
},
{
"Short decl of existing var (y) is an assignment.",
`func f(x int) { y := x; y, z := 1, 2; _, _ = y, z }`,
`[0 -2]`,
},
{
"Unreferenced parameters are excluded.",
`func f(x, y, z int) { _ = z + x }`,
`[2 0]`,
},
{
"Built-in len has no effect.",
`func f(x, y string) { _ = len(y) + len(x) }`,
`[1 0]`,
},
{
"Built-in println has effects.",
`func f(x, y int) { println(y, x) }`,
`[1 0 -2]`,
},
{
"Return has no effect, and no control successor.",
`func f(x, y int) int { return x + y; panic(1) }`,
`[0 1]`,
},
{
"Loops (etc) have unknown effects.",
`func f(x, y bool) { for x { _ = y } }`,
`[0 -2 1]`,
},
{
"Calls have unknown effects.",
`func f(x, y int) { _, _, _ = x, g(), y }; func g() int`,
`[0 -2 1]`,
},
{
"Calls to some built-ins are pure.",
`func f(x, y int) { _, _, _ = x, len("hi"), y }`,
`[0 1]`,
},
{
"Calls to some built-ins are pure (variant).",
`func f(x, y int) { s := "hi"; _, _, _ = x, len(s), y; s = "bye" }`,
`[0 1 -2]`,
},
{
"Calls to some built-ins are pure (another variants).",
`func f(x, y int) { s := "hi"; _, _, _ = x, len(s), y }`,
`[0 1]`,
},
{
"Reading a local var is impure but does not have effects.",
`func f(x, y bool) { for x { _ = y } }`,
`[0 -2 1]`,
},
}
for _, test := range tests {
test := test
t.Run(test.descr, func(t *testing.T) {
fset := token.NewFileSet()
mustParse := func(filename string, content any) *ast.File {
f, err := parser.ParseFile(fset, filename, content, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
t.Fatalf("ParseFile: %v", err)
}
return f
}
// Parse callee file and find first func decl named f.
calleeContent := "package p\n" + test.callee
calleeFile := mustParse("callee.go", calleeContent)
var decl *ast.FuncDecl
for _, d := range calleeFile.Decls {
if d, ok := d.(*ast.FuncDecl); ok && d.Name.Name == funcName {
decl = d
break
}
}
if decl == nil {
t.Fatalf("declaration of func %s not found: %s", funcName, test.callee)
}
info := &types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Types: make(map[ast.Expr]types.TypeAndValue),
Implicits: make(map[ast.Node]types.Object),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
Scopes: make(map[ast.Node]*types.Scope),
}
conf := &types.Config{Error: func(err error) { t.Error(err) }}
pkg, err := conf.Check("p", fset, []*ast.File{calleeFile}, info)
if err != nil {
t.Fatal(err)
}
callee, err := inline.AnalyzeCallee(t.Logf, fset, pkg, info, decl, []byte(calleeContent))
if err != nil {
t.Fatal(err)
}
if got := fmt.Sprint(callee.Effects()); got != test.want {
t.Errorf("for effects of %s, got %s want %s",
test.callee, got, test.want)
}
})
}
}
| tools/internal/refactor/inline/calleefx_test.go/0 | {
"file_path": "tools/internal/refactor/inline/calleefx_test.go",
"repo_id": "tools",
"token_count": 1925
} | 768 |
Test of inlining a function that uses a dot import.
-- go.mod --
module testdata
go 1.12
-- a/a.go --
package a
func A() {}
-- b/b.go --
package b
import . "testdata/a"
func B() { A() }
-- c/c.go --
package c
import "testdata/b"
func _() {
b.B() //@ inline(re"B", result)
}
-- result --
package c
import (
"testdata/a"
)
func _() {
a.A() //@ inline(re"B", result)
}
| tools/internal/refactor/inline/testdata/dotimport.txtar/0 | {
"file_path": "tools/internal/refactor/inline/testdata/dotimport.txtar",
"repo_id": "tools",
"token_count": 169
} | 769 |
Tests of various n-ary result function cases.
-- go.mod --
module testdata
go 1.12
-- a/a.go --
package a
func _() {
println(f1()) //@ inline(re"f1", f1)
}
func f1() (int, int) { return 1, 1 }
-- f1 --
package a
func _() {
println(1, 1) //@ inline(re"f1", f1)
}
func f1() (int, int) { return 1, 1 }
-- b/b.go --
package b
func _() {
f2() //@ inline(re"f2", f2)
}
func f2() (int, int) { return 2, 2 }
-- f2 --
package b
func _() {
_, _ = 2, 2 //@ inline(re"f2", f2)
}
func f2() (int, int) { return 2, 2 }
-- c/c.go --
package c
func _() {
_, _ = f3() //@ inline(re"f3", f3)
}
func f3() (int, int) { return f3A() }
func f3A() (x, y int)
-- f3 --
package c
func _() {
_, _ = f3A() //@ inline(re"f3", f3)
}
func f3() (int, int) { return f3A() }
func f3A() (x, y int)
-- d/d.go --
package d
func _() {
println(-f4()) //@ inline(re"f4", f4)
}
func f4() int { return 2 + 2 }
-- f4 --
package d
func _() {
println(-(2 + 2)) //@ inline(re"f4", f4)
}
func f4() int { return 2 + 2 }
| tools/internal/refactor/inline/testdata/n-ary.txtar/0 | {
"file_path": "tools/internal/refactor/inline/testdata/n-ary.txtar",
"repo_id": "tools",
"token_count": 490
} | 770 |
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The gostacks command processes stdin looking for things that look like
// stack traces and simplifying them to make the log more readable.
// It collates stack traces that have the same path as well as simplifying the
// individual lines of the trace.
// The processed log is printed to stdout.
package main
import (
"fmt"
"os"
"golang.org/x/tools/internal/stack"
)
func main() {
if err := stack.Process(os.Stdout, os.Stdin); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
| tools/internal/stack/gostacks/gostacks.go/0 | {
"file_path": "tools/internal/stack/gostacks/gostacks.go",
"repo_id": "tools",
"token_count": 198
} | 771 |
//go:build go1.22
package versions // want "post.go@go1.22"
| tools/internal/testfiles/testdata/versions/post.go/0 | {
"file_path": "tools/internal/testfiles/testdata/versions/post.go",
"repo_id": "tools",
"token_count": 25
} | 772 |
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package typeparams
import (
"errors"
"fmt"
"go/types"
"os"
"strings"
)
//go:generate go run copytermlist.go
const debug = false
var ErrEmptyTypeSet = errors.New("empty type set")
// StructuralTerms returns a slice of terms representing the normalized
// structural type restrictions of a type parameter, if any.
//
// Structural type restrictions of a type parameter are created via
// non-interface types embedded in its constraint interface (directly, or via a
// chain of interface embeddings). For example, in the declaration
//
// type T[P interface{~int; m()}] int
//
// the structural restriction of the type parameter P is ~int.
//
// With interface embedding and unions, the specification of structural type
// restrictions may be arbitrarily complex. For example, consider the
// following:
//
// type A interface{ ~string|~[]byte }
//
// type B interface{ int|string }
//
// type C interface { ~string|~int }
//
// type T[P interface{ A|B; C }] int
//
// In this example, the structural type restriction of P is ~string|int: A|B
// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int,
// which when intersected with C (~string|~int) yields ~string|int.
//
// StructuralTerms computes these expansions and reductions, producing a
// "normalized" form of the embeddings. A structural restriction is normalized
// if it is a single union containing no interface terms, and is minimal in the
// sense that removing any term changes the set of types satisfying the
// constraint. It is left as a proof for the reader that, modulo sorting, there
// is exactly one such normalized form.
//
// Because the minimal representation always takes this form, StructuralTerms
// returns a slice of tilde terms corresponding to the terms of the union in
// the normalized structural restriction. An error is returned if the
// constraint interface is invalid, exceeds complexity bounds, or has an empty
// type set. In the latter case, StructuralTerms returns ErrEmptyTypeSet.
//
// StructuralTerms makes no guarantees about the order of terms, except that it
// is deterministic.
func StructuralTerms(tparam *types.TypeParam) ([]*types.Term, error) {
constraint := tparam.Constraint()
if constraint == nil {
return nil, fmt.Errorf("%s has nil constraint", tparam)
}
iface, _ := constraint.Underlying().(*types.Interface)
if iface == nil {
return nil, fmt.Errorf("constraint is %T, not *types.Interface", constraint.Underlying())
}
return InterfaceTermSet(iface)
}
// InterfaceTermSet computes the normalized terms for a constraint interface,
// returning an error if the term set cannot be computed or is empty. In the
// latter case, the error will be ErrEmptyTypeSet.
//
// See the documentation of StructuralTerms for more information on
// normalization.
func InterfaceTermSet(iface *types.Interface) ([]*types.Term, error) {
return computeTermSet(iface)
}
// UnionTermSet computes the normalized terms for a union, returning an error
// if the term set cannot be computed or is empty. In the latter case, the
// error will be ErrEmptyTypeSet.
//
// See the documentation of StructuralTerms for more information on
// normalization.
func UnionTermSet(union *types.Union) ([]*types.Term, error) {
return computeTermSet(union)
}
func computeTermSet(typ types.Type) ([]*types.Term, error) {
tset, err := computeTermSetInternal(typ, make(map[types.Type]*termSet), 0)
if err != nil {
return nil, err
}
if tset.terms.isEmpty() {
return nil, ErrEmptyTypeSet
}
if tset.terms.isAll() {
return nil, nil
}
var terms []*types.Term
for _, term := range tset.terms {
terms = append(terms, types.NewTerm(term.tilde, term.typ))
}
return terms, nil
}
// A termSet holds the normalized set of terms for a given type.
//
// The name termSet is intentionally distinct from 'type set': a type set is
// all types that implement a type (and includes method restrictions), whereas
// a term set just represents the structural restrictions on a type.
type termSet struct {
complete bool
terms termlist
}
func indentf(depth int, format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, strings.Repeat(".", depth)+format+"\n", args...)
}
func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth int) (res *termSet, err error) {
if t == nil {
panic("nil type")
}
if debug {
indentf(depth, "%s", t.String())
defer func() {
if err != nil {
indentf(depth, "=> %s", err)
} else {
indentf(depth, "=> %s", res.terms.String())
}
}()
}
const maxTermCount = 100
if tset, ok := seen[t]; ok {
if !tset.complete {
return nil, fmt.Errorf("cycle detected in the declaration of %s", t)
}
return tset, nil
}
// Mark the current type as seen to avoid infinite recursion.
tset := new(termSet)
defer func() {
tset.complete = true
}()
seen[t] = tset
switch u := t.Underlying().(type) {
case *types.Interface:
// The term set of an interface is the intersection of the term sets of its
// embedded types.
tset.terms = allTermlist
for i := 0; i < u.NumEmbeddeds(); i++ {
embedded := u.EmbeddedType(i)
if _, ok := embedded.Underlying().(*types.TypeParam); ok {
return nil, fmt.Errorf("invalid embedded type %T", embedded)
}
tset2, err := computeTermSetInternal(embedded, seen, depth+1)
if err != nil {
return nil, err
}
tset.terms = tset.terms.intersect(tset2.terms)
}
case *types.Union:
// The term set of a union is the union of term sets of its terms.
tset.terms = nil
for i := 0; i < u.Len(); i++ {
t := u.Term(i)
var terms termlist
switch t.Type().Underlying().(type) {
case *types.Interface:
tset2, err := computeTermSetInternal(t.Type(), seen, depth+1)
if err != nil {
return nil, err
}
terms = tset2.terms
case *types.TypeParam, *types.Union:
// A stand-alone type parameter or union is not permitted as union
// term.
return nil, fmt.Errorf("invalid union term %T", t)
default:
if t.Type() == types.Typ[types.Invalid] {
continue
}
terms = termlist{{t.Tilde(), t.Type()}}
}
tset.terms = tset.terms.union(terms)
if len(tset.terms) > maxTermCount {
return nil, fmt.Errorf("exceeded max term count %d", maxTermCount)
}
}
case *types.TypeParam:
panic("unreachable")
default:
// For all other types, the term set is just a single non-tilde term
// holding the type itself.
if u != types.Typ[types.Invalid] {
tset.terms = termlist{{false, t}}
}
}
return tset, nil
}
// under is a facade for the go/types internal function of the same name. It is
// used by typeterm.go.
func under(t types.Type) types.Type {
return t.Underlying()
}
| tools/internal/typeparams/normalize.go/0 | {
"file_path": "tools/internal/typeparams/normalize.go",
"repo_id": "tools",
"token_count": 2255
} | 773 |
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package versions
import (
"go/types"
)
// GoVersion returns the Go version of the type package.
// It returns zero if no version can be determined.
func GoVersion(pkg *types.Package) string {
// TODO(taking): x/tools can call GoVersion() [from 1.21] after 1.25.
if pkg, ok := any(pkg).(interface{ GoVersion() string }); ok {
return pkg.GoVersion()
}
return ""
}
| tools/internal/versions/types.go/0 | {
"file_path": "tools/internal/versions/types.go",
"repo_id": "tools",
"token_count": 165
} | 774 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package present
import (
"fmt"
"strings"
)
func init() {
Register("iframe", parseIframe)
}
type Iframe struct {
Cmd string // original command from present source
URL string
Width int
Height int
}
func (i Iframe) PresentCmd() string { return i.Cmd }
func (i Iframe) TemplateName() string { return "iframe" }
func parseIframe(ctx *Context, fileName string, lineno int, text string) (Elem, error) {
args := strings.Fields(text)
if len(args) < 2 {
return nil, fmt.Errorf("incorrect iframe invocation: %q", text)
}
i := Iframe{Cmd: text, URL: args[1]}
a, err := parseArgs(fileName, lineno, args[2:])
if err != nil {
return nil, err
}
switch len(a) {
case 0:
// no size parameters
case 2:
if v, ok := a[0].(int); ok {
i.Height = v
}
if v, ok := a[1].(int); ok {
i.Width = v
}
default:
return nil, fmt.Errorf("incorrect iframe invocation: %q", text)
}
return i, nil
}
| tools/present/iframe.go/0 | {
"file_path": "tools/present/iframe.go",
"repo_id": "tools",
"token_count": 405
} | 775 |
<!-- media.html -->
| tools/present/testdata/media.html/0 | {
"file_path": "tools/present/testdata/media.html",
"repo_id": "tools",
"token_count": 7
} | 776 |
package template
// Basic test of expression refactoring.
// (Types are not important in this case; it could be done with gofmt -r.)
import "time"
func before(t time.Time) time.Duration { return time.Now().Sub(t) }
func after(t time.Time) time.Duration { return time.Since(t) }
| tools/refactor/eg/testdata/B.template/0 | {
"file_path": "tools/refactor/eg/testdata/B.template",
"repo_id": "tools",
"token_count": 88
} | 777 |
package G1
import "go/ast"
func example() {
_ = ast.BadExpr{From: 123, To: 456} // match
_ = ast.BadExpr{123, 456} // no match
_ = ast.BadExpr{From: 123} // no match
_ = ast.BadExpr{To: 456} // no match
}
| tools/refactor/eg/testdata/G1.go/0 | {
"file_path": "tools/refactor/eg/testdata/G1.go",
"repo_id": "tools",
"token_count": 124
} | 778 |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package importgraph computes the forward and reverse import
// dependency graphs for all packages in a Go workspace.
package importgraph // import "golang.org/x/tools/refactor/importgraph"
import (
"go/build"
"sync"
"golang.org/x/tools/go/buildutil"
)
// A Graph is an import dependency graph, either forward or reverse.
//
// The graph maps each node (a package import path) to the set of its
// successors in the graph. For a forward graph, this is the set of
// imported packages (prerequisites); for a reverse graph, it is the set
// of importing packages (clients).
//
// Graph construction inspects all imports in each package's directory,
// including those in _test.go files, so the resulting graph may be cyclic.
type Graph map[string]map[string]bool
func (g Graph) addEdge(from, to string) {
edges := g[from]
if edges == nil {
edges = make(map[string]bool)
g[from] = edges
}
edges[to] = true
}
// Search returns all the nodes of the graph reachable from
// any of the specified roots, by following edges forwards.
// Relationally, this is the reflexive transitive closure.
func (g Graph) Search(roots ...string) map[string]bool {
seen := make(map[string]bool)
var visit func(x string)
visit = func(x string) {
if !seen[x] {
seen[x] = true
for y := range g[x] {
visit(y)
}
}
}
for _, root := range roots {
visit(root)
}
return seen
}
// Build scans the specified Go workspace and builds the forward and
// reverse import dependency graphs for all its packages.
// It also returns a mapping from canonical import paths to errors for packages
// whose loading was not entirely successful.
// A package may appear in the graph and in the errors mapping.
// All package paths are canonical and may contain "/vendor/".
func Build(ctxt *build.Context) (forward, reverse Graph, errors map[string]error) {
type importEdge struct {
from, to string
}
type pathError struct {
path string
err error
}
ch := make(chan interface{})
go func() {
sema := make(chan int, 20) // I/O concurrency limiting semaphore
var wg sync.WaitGroup
buildutil.ForEachPackage(ctxt, func(path string, err error) {
if err != nil {
ch <- pathError{path, err}
return
}
wg.Add(1)
go func() {
defer wg.Done()
sema <- 1
bp, err := ctxt.Import(path, "", 0)
<-sema
if err != nil {
if _, ok := err.(*build.NoGoError); ok {
// empty directory is not an error
} else {
ch <- pathError{path, err}
}
// Even in error cases, Import usually returns a package.
}
// absolutize resolves an import path relative
// to the current package bp.
// The absolute form may contain "vendor".
//
// The vendoring feature slows down Build by 3×.
// Here are timings from a 1400 package workspace:
// 1100ms: current code (with vendor check)
// 880ms: with a nonblocking cache around ctxt.IsDir
// 840ms: nonblocking cache with duplicate suppression
// 340ms: original code (no vendor check)
// TODO(adonovan): optimize, somehow.
memo := make(map[string]string)
absolutize := func(path string) string {
canon, ok := memo[path]
if !ok {
sema <- 1
bp2, _ := ctxt.Import(path, bp.Dir, build.FindOnly)
<-sema
if bp2 != nil {
canon = bp2.ImportPath
} else {
canon = path
}
memo[path] = canon
}
return canon
}
if bp != nil {
for _, imp := range bp.Imports {
ch <- importEdge{path, absolutize(imp)}
}
for _, imp := range bp.TestImports {
ch <- importEdge{path, absolutize(imp)}
}
for _, imp := range bp.XTestImports {
ch <- importEdge{path, absolutize(imp)}
}
}
}()
})
wg.Wait()
close(ch)
}()
forward = make(Graph)
reverse = make(Graph)
for e := range ch {
switch e := e.(type) {
case pathError:
if errors == nil {
errors = make(map[string]error)
}
errors[e.path] = e.err
case importEdge:
if e.to == "C" {
continue // "C" is fake
}
forward.addEdge(e.from, e.to)
reverse.addEdge(e.to, e.from)
}
}
return forward, reverse, errors
}
| tools/refactor/importgraph/graph.go/0 | {
"file_path": "tools/refactor/importgraph/graph.go",
"repo_id": "tools",
"token_count": 1656
} | 779 |
# This Docker container is used for testing on GCB.
ARG GOVERSION=1
FROM golang:${GOVERSION} AS gobuilder
ENV GOBIN /gobin
# Install other Go tools tests depend on
RUN mkdir -p /scratch/installtools
ADD extension/tools/installtools/main.go /scratch/installtools/main.go
RUN go run /scratch/installtools/main.go
FROM node:latest
# GO111MODULE=auto
RUN mkdir /go
COPY --from=gobuilder /gobin /go/bin
COPY --from=gobuilder /usr/local/go /usr/local/go
# Add the default GOPATH/bin to the PATH.
# Add the directories of the go tool chains to PATH.
ENV PATH /go/bin:/usr/local/go/bin:${PATH}
ENV DEBIAN_FRONTEND noninteractive
# Force npm to prefer ipv4 - the vm we are using doesn't yet support ipv6.
# TODO(hyangah): remove this when the platform works with ipv6.
ENV NODE_OPTIONS --dns-result-order=ipv4first
# Install xvfb jq
RUN apt-get -qq update && apt-get install -qq -y libnss3 libgtk-3-dev libxss1 libasound2 xvfb libsecret-1-0 jq > /dev/null
# Install gh https://stackoverflow.com/a/69477930
RUN apt update && apt install -y \
curl \
gpg
RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | gpg --dearmor -o /usr/share/keyrings/githubcli-archive-keyring.gpg;
RUN echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null;
RUN apt update && apt install -y gh;
USER node
WORKDIR /workspace
ENTRYPOINT ["build/all.bash"] | vscode-go/build/Dockerfile/0 | {
"file_path": "vscode-go/build/Dockerfile",
"repo_id": "vscode-go",
"token_count": 562
} | 780 |
# Debugging with Legacy Debug Adapter
The Go extension historically used a small adapter program to work with the Go debugger, [Delve].
The extension transitioned to communicate with [Delve] directly but there are still cases you may
need to use the legacy debug adapter (e.g. remote debugging). This document explains how to use the
***legacy*** debug adapter.
* [Set up](#set-up)
* [Installation](#installation)
* [Configuration](#configuration)
* [Launch Configurations](#launch-configurations)
* [Specifying build tags](#specifying-build-tags)
* [Specifying other build flags](#specifying-other-build-flags)
* [Using VS Code Variables](#using-vs-code-variables)
* [Snippets](#snippets)
* [Debugging on Windows Subsystem for Linux (WSL)](#debugging-on-windows-subsystem-for-linux-wsl)
* [Remote Debugging](#remote-debugging)
* [Troubleshooting](#troubleshooting)
* [Read documentation and common issues](#read-documentation-and-common-issues)
* [Update Delve](#update-delve)
* [Check for multiple versions of Delve](#check-for-multiple-versions-of-delve)
* [Check your launch configuration](#check-your-launch-configuration)
* [Check your GOPATH](#check-your-gopath)
* [Enable logging](#enable-logging)
* [Optional: Debug the debugger](#optional-debug-the-debugger)
* [Ask for help](#ask-for-help)
* [Common issues](#common-issues)
## Set up
[Delve] (`dlv`) should be installed by default when you install this extension.
You may need to update `dlv` to the latest version to support the latest version
of Go. To install or update `dlv`, open the [Command Palette][]
(Windows/Linux: Ctrl+Shift+P; OSX: Shift+Command+P), select [`Go: Install/Update Tools`](settings.md#go-installupdate-tools), and select [`dlv`](tools.md#dlv).
## Selecting `legacy` debug adapter
To opt in to use the legacy debug adapter (`legacy`) by default, add the following in your VSCode settings.json.
```
"go.delveConfig": {
"debugAdapter": "legacy",
}
```
If you want to use the legacy mode for only a subset of your launch configurations, you can use [the `debugAdapter` attribute](#launchjson-attributes) to switch between `"dlv-dap"` and `"legacy"` mode.
For [Remote Debugging](#remote-debugging) (launch configuration with `"mode": "remote"` attribute),
the extension will use the `"legacy"` mode by default, so setting this attribute won't be necessary.
Throughout this document, we assume that you opted in to use the legacy debug adapter.
For debugging using the new debug adapter (default, `"dlv-dap"` mode), please see the documentation about [Debugging](https://github.com/golang/vscode-go/tree/master/docs/debugging-legacy.md).
### Configuration
You may not need to configure any settings to start debugging your programs, but you should be aware that the debugger looks at the following settings.
* Related to [`GOPATH`](gopath.md):
* [`go.gopath`](settings.md#go.gopath)
* [`go.inferGopath`](settings.md#go.inferGopath)
* [`go.delveConfig`](settings.md#go.delveConfig)
* `apiVersion`: Controls the version of the Delve API used (default: `2`).
* `dlvLoadConfig`: The configuration passed to Delve, which controls how variables are shown in the Debug pane. Not applicable when `apiVersion` is 1.
* `maxStringLen`: Maximum number of bytes read from a string (default: `64`).
* `maxArrayValues`: Maximum number of elements read from an array, slice, or map (default: `64`).
* `maxStructFields`: Maximum number of fields read from a struct. A setting of `-1` indicates that all fields should be read (default: `-1`).
* `maxVariableRecurse`: How far to recurse when evaluating nested types (default: `1`).
* `followPointers`: Automatically dereference pointers (default: `true`).
* `showGlobalVariables`: Show global variables in the Debug view (default: `false`).
* `debugAdapter`: Controls which debug adapter to use (default: `legacy`).
* `substitutePath`: Path mappings to apply to get from a path in the editor to a path in the compiled program (default: `[]`).
There are some common cases when you might want to tweak the Delve configurations.
* To change the default cap of 64 on string and array length when inspecting variables in the Debug view, set `maxStringLen`. (See a related known issue: [golang/vscode-go#126](https://github.com/golang/vscode-go/issues/126)).
* To evaluate nested variables in the Run view, set `maxVariableRecurse`.
## Launch Configurations
To get started debugging, run the command `Debug: Open launch.json`. If you did not already have a `launch.json` file for your project, this will create one for you. It will contain this default configuration, which can be used to debug the current package. With mode `auto`, the file that is currently open will determine whether to debug the program as a test. If `program` is instead set to a Go file, that file will determine which mode to run in.
```json5
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}",
"debugAdapter": "legacy",
"env": {},
"args": []
}
]
}
```
There are some more properties that you can adjust in the debug configuration:
Property | Description
-------- | -----------
name | The name for your configuration as it appears in the drop-down in the Run view.
type | Always leave this set to `"go"`. VS Code uses this setting to determine which extension should be used for debugging.
request | One of `launch` or `attach`. Use `attach` when you want to attach to a running process.
mode | For `launch` requests, one of `auto`, `debug`, `remote`, `test`, or `exec`. For `attach` requests, use `local` or `remote`.
program | In `test` or `debug` mode, this refers to the absolute path to the package or file to debug. In `exec` mode, this is the existing binary file to debug. Not applicable to `attach` requests.
env | Environment variables to use when debugging. Use the format: `{ "NAME": "VALUE" }`. Not applicable to `attach` requests.
envFile | Absolute path to a file containing environment variable definitions. The environment variables passed in via the `env` property override the ones in this file.
args | Array of command-line arguments to pass to the program being debugged.
showLog | If `true` and `logDest` is not set, Delve logs will be printed in the Debug Console panel. If `true` and `logDest` is set, logs will be written to the `logDest` file. This corresponds to `dlv`'s `--log` flag.
logOutput | Comma-separated list of Delve components (`debugger`, `gdbwire`, `lldbout`, `debuglineerr`, `rpc`) that should produce debug output when `showLog` is `true`. This corresponds to `dlv`'s `--log-output` flag.
logDest | Absolute path to the delve log output file. This corresponds to `dlv`'s `--log-dest` flag, but number (used for file descriptor) is disallowed. Supported only in dlv-dap mode on Linux and Mac.
buildFlags | Build flags to pass to the Go compiler. This corresponds to `dlv`'s `--build-flags` flag.
dlvFlags | Extra flags passed to `dlv`. See `dlv help` for the full list of supported flags. This is useful when users need to pass less commonly used or new flags such as `--only-same-user`, `--check-go-version`. Note that some flags such as `--log-output`, `--log`, `--log-dest`, `--api-version` already have corresponding properties in the debug configuration, and flags such as `--listen` and `--headless` are used internally. If they are specified in `dlvFlags`, they may be ignored or cause an error.
remotePath | If remote debugging (`mode`: `remote`), this should be the absolute path to the package being debugged on the remote machine. See the section on [Remote Debugging](#remote-debugging) for further details. [golang/vscode-go#45](https://github.com/golang/vscode-go/issues/45) is also relevant. Becomes the first mapping in substitutePath.
substitutePath | An array of mappings from an absolute local path to an absolute remote path that is used by the debuggee. The debug adapter will replace the local path with the remote path in all of the calls. The mappings are applied in order, and the first matching mapping is used. This can be used to map files that have moved since the program was built, different remote paths, and symlinked files or directories. This is intended to be equivalent to the [substitute-path](https://github.com/go-delve/delve/tree/master/Documentation/cli#config) configuration, and will eventually configure substitute-path in Delve directly.
cwd | The working directory to be used in running the program. If remote debugging (`mode`: `remote`), this should be the absolute path to the working directory being debugged on the local machine. The extension defaults to the workspace folder, or the workspace folder of the open file in multi root workspaces. See the section on [Remote Debugging](#remote-debugging) for further details. [golang/vscode-go#45](https://github.com/golang/vscode-go/issues/45) is also relevant.
processId | This is the process ID of the executable you want to debug. Applicable only when using the `attach` request in `local` mode. By setting this to the command name of the process, `${command:pickProcess}`, or`${command:pickGoProcess}` a quick pick menu will show a list of processes to choose from.
### Specifying [build tags](https://golang.org/pkg/go/build/#hdr-Build_Constraints)
If your program contains [build tags](https://golang.org/pkg/go/build/#hdr-Build_Constraints), you can use the `buildFlags` property. For example, if you build your code with:
```bash
go build -tags=whatever
```
Then, set:
```json5
"buildFlags": "-tags=whatever"
```
in your launch configuration. This property supports multiple tags, which you can set by using single quotes. For example:
```json5
"buildFlags": "-tags='first,second,third'"
```
<!--TODO(rstambler): Confirm that the extension works with a comma (not space) separated list.-->
### Specifying other build flags
The flags specified in `buildFlags` and `env.GOFLAGS` are passed to the Go compiler when building your program for debugging. Delve adds `-gcflags=all="-N -l"` to the list of build flags to disable optimizations. User specified buildFlags conflict with this setting, so the extension removes them ([Issue #117](https://github.com/golang/vscode-go/issues/117)). If you wish to debug a program using custom `-gcflags`, build the program using `go build` and launch using `exec` mode:
```json
{
"name": "Launch executable",
"type": "go",
"request": "launch",
"mode": "exec",
"program": "/absolute/path/to/executable"
}
```
Note that it is not recommended to debug optimized executables as Delve may not have the information necessary to properly debug your program.
### Using [VS Code variables]
Any property in the launch configuration that requires a file path can be specified in terms of [VS Code variables]. Here are some useful ones to know:
* `${workspaceFolder}` refers to the root of the workspace opened in VS Code. If using a multi root workspace, you must specify the folder name `${workspaceFolder:folderName}`
* `${fileWorkspaceFolder}` refers to the the current opened file's workspace folder.
* `${file}` refers to the currently opened file.
* `${fileDirname}` refers to the directory containing the currently opened file. This is typically also the name of the Go package containing this file, and as such, can be used to debug the currently opened package.
### Snippets
In addition to [VS Code variables], you can make use of [snippets] when editing the launch configuration in `launch.json`.
When you type `go` in the `launch.json` file, you will see snippet suggestions for debugging the current file or package or a given test function.
Below are the available sample configurations:
#### Debug the current file (`Go: Launch file`)
Recall that `${file}` refers to the currently opened file (see [Using VS Code Variables](#using-vs-code-variables)). For debugging a package that consists with multiple files, use `${fileDirname}` instead.
```json5
{
"name": "Launch file",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${file}"
}
```
#### Debug a single test function (`Go: Launch test function`)
Recall that `${workspaceFolder}` refers to the current workspace (see [Using VS Code Variables](#using-vs-code-variables)). You will need to manually specify the function name instead of `"MyTestFunction"`.
```json5
{
"name": "Launch test function",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}",
"args": [
"-test.run",
"MyTestFunction"
]
}
```
#### Debug all tests in the given package (`Go: Launch test package`)
A package is a collection of source files in the same directory that are compiled together.
Recall that `${fileDirname}` refers to the directory of the open file (see [Using VS Code Variables](#using-vs-code-variables)).
```json5
{
"name": "Launch test package",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}"
}
```
#### Attach to a running local process via its process ID (`Go: Attach to local process`)
Substitute `processName` with the name of the local process.
```json5
{
"name": "Attach to local process",
"type": "go",
"request": "attach",
"mode": "local",
"processId": "processName"
}
```
#### Attach to a running server (`Go: Connect to Server`)
```json5
{
"name": "Connect to server",
"type": "go",
"request": "attach",
"mode": "remote",
"remotePath": "${workspaceFolder}",
"port": 2345,
"host": "127.0.0.1"
}
```
#### Debug an existing binary
There is no snippet suggestion for this configuration.
```json
{
"name": "Launch executable",
"type": "go",
"request": "launch",
"mode": "exec",
"program": "/absolute/path/to/executable"
}
```
If passing arguments to or calling subcommands and flags from a binary, the `args` property can be used.
```json
{
"name": "Launch executable",
"type": "go",
"request": "launch",
"mode": "exec",
"program": "/absolute/path/to/executable",
"args": ["subcommand", "arg", "--flag"],
}
```
## Debugging on [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/)
If you are using using WSL, you will need the WSL 2 Linux kernel. See [WSL 2 Installation](https://docs.microsoft.com/en-us/windows/wsl/wsl2-install) and note the Window 10 build version requirements.
## Remote Debugging
<!--TODO(quoctruong): We use "remote" and "target", as well as "local" here. We should define these terms more clearly and be consistent about which we use.-->
To debug on a remote machine, you must first run a headless Delve server on the target machine. The examples below assume that you are in the same folder as the package you want to debug. If not, please refer to the [`dlv debug` documentation](https://github.com/go-delve/delve/blob/master/Documentation/usage/dlv_debug.md).
To start the headless Delve server:
```bash
dlv debug --headless --listen=:2345 --log --api-version=2
```
Any arguments that you want to pass to the program you are debugging must also be passed to this Delve server. For example:
```bash
dlv debug --headless --listen=:2345 --log -- -myArg=123
```
Then, create a remote debug configuration in your `launch.json`.
```json5
{
"name": "Launch remote",
"type": "go",
"request": "attach",
"mode": "remote",
"remotePath": "/absolute/path/dir/on/remote/machine",
"port": 2345,
"host": "127.0.0.1",
"cwd": "/absolute/path/dir/on/local/machine",
}
```
In the example, the VS Code debugger will run on the same machine as the headless `dlv` server. Make sure to update the `port` and `host` settings to point to your remote machine.
`remotePath` should point to the absolute path of the program being debugged in the remote machine. `cwd` should point to the absolute path of the working directory of the program being debugged on your local machine. This should be the counterpart of the folder in `remotePath`. See [golang/vscode-go#45](https://github.com/golang/vscode-go/issues/45) for updates regarding `remotePath` and `cwd`. You can also use the equivalent `substitutePath` configuration.
```json5
{
"name": "Launch remote",
"type": "go",
"request": "attach",
"mode": "remote",
"substitutePath": [
{
"from": "/absolute/path/dir/on/local/machine",
"to": "/absolute/path/dir/on/remote/machine",
},
],
"port": 2345,
"host": "127.0.0.1",
"cwd": "/absolute/path/dir/on/local/machine",
}
```
If you do not set, `remotePath` or `substitutePath`, then the debug adapter will attempt to infer the path mappings. See [golang/vscode-go#45](https://github.com/golang/vscode-go/issues/45) for more information.
When you run the `Launch remote` target, VS Code will send debugging commands to the `dlv` server you started, instead of launching it's own `dlv` instance against your program.
For further examples, see [this launch configuration for a process running in a Docker host](https://github.com/lukehoban/webapp-go/tree/debugging).
## Troubleshooting
Debugging is one of the most complex features offered by this extension. The features are not complete, and a new implementation is currently being developed (see [golang/vscode-go#23](https://github.com/golang/vscode-go/issues/23)).
The suggestions below are intended to help you troubleshoot any problems you encounter. If you are unable to resolve the issue, please take a look at the [current known debugging issues](https://github.com/golang/vscode-go/issues?q=is%3Aissue+is%3Aopen+label%3Adebug) or [file a new issue](https://github.com/golang/vscode-go/issues/new/choose).
### Read documentation and [common issues](#common-issues)
Start by taking a quick glance at the [common issues](#common-issues) described below. You can also check the [Delve FAQ](https://github.com/go-delve/delve/blob/master/Documentation/faq.md) in case the problem is mentioned there.
### Update Delve
If the problem persists, it's time to start troubleshooting. A good first step is to make sure that you are working with the latest version of Delve. You can do this by running the [`Go: Install/Update Tools`](settings.md#go-installupdate-tools) command and selecting [`dlv`](tools.md#dlv).
### Check your [launch configuration](#launch-configurations)
Next, confirm that your [launch configuration](#launch-configurations) is correct.
One common error is `could not launch process: stat ***/debug.test: no such file or directory`. You may see this while running in the `test` mode. This happens when the `program` attribute points to a folder with no test files, so ensure that the `program` attribute points to a directory containing the test files you wish to debug.
Also, check the version of the Delve API used in your [launch configuration](#launch-configurations). This is handled by the `–api-version` flag, `2` is the default. If you are debugging on a remote machine, this is particularly important, as the versions on the local and remote machines much match. You can change the API version by editing the [`launch.json` file](#launch-configurations).
### Check for multiple versions of Delve
You might have multiple different versions of [`dlv`](tools.md#dlv) installed, and VS Code Go could be using a wrong or old version. Run the [`Go: Locate Configured Go Tools`](settings.md#go-locate-configured-go-tools) command and see where VS Code Go has found `dlv` on your machine. You can try running `which dlv` to see which version of `dlv` you are using on the [command-line](https://github.com/go-delve/delve/tree/master/Documentation/cli).
To fix the issue, simply delete the version of `dlv` used by the Go extension. Note that the extension first searches for binaries in your `$GOPATH/bin` and then looks on your `$PATH`.
If you see the error message `Failed to continue: "Error: spawn EACCES"`, the issue is probably multiple versions of `dlv`.
### Try building your binary **without** compiler optimizations
If you notice `Unverified breakpoints` or missing variables, ensure that your binary was built **without** compiler optimizations. Try building the binary with `-gcflags="all=-N -l"`.
### Check your `GOPATH`
Make sure that the debugger is using the right [`GOPATH`](gopath.md). This is probably the issue if you see `Cannot find package ".." in any of ...` errors. Read more about configuring your [GOPATH](gopath.md) or [file an issue report](https://github.com/golang/vscode-go/issues/new/choose).
**As a work-around**, add the correct `GOPATH` as an environment variable in the `env` property in the `launch.json` file.
### Enable logging
Next, check the logs produced by Delve. These will need to be manually enabled. Follow these steps:
* Set `"showLog": true` in your launch configuration. This will show Delve logs in the Debug Console pane (Ctrl+Shift+Y).
* Set `"trace": "log"` in your launch configuration. Again, you will see logs in the Debug Console pane (Ctrl+Shift+Y). These logs will also be saved to a file and the path to this file will be printed at the top of the Debug Console.
* Set `"logOutput": "rpc"` in your launch configuration. You will see logs of the RPC messages going between VS Code and Delve. Note that for this to work, you must also have set `"showLog": true`.
* The `logOutput` attribute corresponds to the `--log-output` flag used by Delve. It is a comma-separated list of components that should produce debug output.
See [common issues](#common-issues) below to decipher error messages you may find in your logs.
With `"trace": "log"`, you will see the actual call being made to `dlv`. To aid in your investigation, you can copy that and run it in your terminal.
### **Optional**: Debug the debugger
This is not a required step, but if you want to continue digging deeper, you can, in fact, debug the debugger. The code for the debugger can be found in the [debug adapter module](../src/debugAdapter). See our [contribution guide](contributing.md) to learn how to [run](contributing.md#run) and [sideload](contributing.md#sideload) the Go extension.
### Ask for help
At this point, it's time to look at the [common issues](#common-issues) below or the [existing debugging issues](https://github.com/golang/vscode-go/issues?q=is%3Aissue+is%3Aopen+label%3Adebug) on the [issue tracker](https://github.com/golang/vscode-go/issues). If that still doesn't solve your problem, [file a new issue](https://github.com/golang/vscode-go/issues/new/choose).
## Common Issues
### delve/launch hangs with no messages on WSL
Try running ```delve debug ./main``` in the WSL command line and see if you get a prompt.
**_Solution_**: Ensure you are running the WSL 2 Kernel, which (as of 4/15/2020) requires an early release of the Windows 10 OS. This is available to anyone via the Windows Insider program. See [Debugging on WSL](#debugging-on-windows-subsystem-for-linux-wsl).
### could not launch process: could not fork/exec
The solution this issue differs based on your OS.
#### OSX
This usually happens on OSX due to signing issues. See the discussions in [Microsoft/vscode-go#717](https://github.com/Microsoft/vscode-go/issues/717), [Microsoft/vscode-go#269](https://github.com/Microsoft/vscode-go/issues/269) and [go-delve/delve#357](https://github.com/go-delve/delve/issues/357).
**_Solution_**: You may have to uninstall dlv and install it manually as described in the [Delve instructions](https://github.com/go-delve/delve/blob/master/Documentation/installation/osx/install.md#manual-install).
#### Linux/Docker
Docker has security settings preventing `ptrace(2)` operations by default within the container.
**_Solution_**: To run your container insecurely, pass `--security-opt=seccomp:unconfined` to `docker run`. See [go-delve/delve#515](https://github.com/go-delve/delve/issues/515) for references.
#### could not launch process: exec: "lldb-server": executable file not found in $PATH
This error can show up for Mac users using Delve versions 0.12.2 and above. `xcode-select --install` has solved the problem for a number of users.
### Debugging symlink directories
Since the debugger and go compiler use the actual filenames, extra configuration is required to debug symlinked directories. Use the `substitutePath` property to tell the debugAdapter how to properly translate the paths. For example, if your project lives in `/path/to/actual/helloWorld`, but the project is open in vscode under the linked folder `/path/to/hello`, you can add the following to your config to set breakpoints in the files in `/path/to/hello`:
```json5
{
"name": "Launch remote",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "/path/to/hello",
"substitutePath": [
{
"from": "/path/to/hello",
"to": "/path/to/actual/helloWorld",
},
],
}
```
This extension does not provide general support for debugging projects containing symlinks. If `substitutePath` does not meet your needs, please consider commenting on this issue that contains updates to symlink support reference [golang/vscode-go#622](https://github.com/golang/vscode-go/issues/622).
[Delve]: https://github.com/go-delve/delve
[VS Code variables]: https://code.visualstudio.com/docs/editor/variables-reference
[snippets]: https://code.visualstudio.com/docs/editor/userdefinedsnippets
[Command Palette]: https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette
| vscode-go/docs/debugging-legacy.md/0 | {
"file_path": "vscode-go/docs/debugging-legacy.md",
"repo_id": "vscode-go",
"token_count": 7691
} | 781 |
{
"extends": "./node_modules/gts/",
"root": true
}
| vscode-go/extension/.eslintrc.json/0 | {
"file_path": "vscode-go/extension/.eslintrc.json",
"repo_id": "vscode-go",
"token_count": 26
} | 782 |
# Debug Adapter
See the [contribution documentation](../../docs/contributing.md) to learn how to develop the debug adapter.
| vscode-go/extension/src/debugAdapter/README.md/0 | {
"file_path": "vscode-go/extension/src/debugAdapter/README.md",
"repo_id": "vscode-go",
"token_count": 32
} | 783 |
/*---------------------------------------------------------
* Copyright 2022 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
import vscode = require('vscode');
import vscodeUri = require('vscode-uri');
import os = require('os');
import path = require('path');
import { getGoConfig, getGoplsConfig } from './config';
import { getBinPath } from './util';
import { getConfiguredTools } from './goTools';
import { inspectGoToolVersion } from './goInstallTools';
import { runGoEnv } from './goModules';
/**
* GoExplorerProvider provides data for the Go tree view in the Explorer
* Tree View Container.
*/
export class GoExplorerProvider implements vscode.TreeDataProvider<vscode.TreeItem> {
private goEnvCache = new Cache((uri) => GoEnv.get(uri ? vscode.Uri.parse(uri) : undefined), Time.MINUTE);
private toolDetailCache = new Cache((name) => getToolDetail(name), Time.HOUR);
private activeFolder?: vscode.WorkspaceFolder;
private activeDocument?: vscode.TextDocument;
static setup(ctx: vscode.ExtensionContext) {
const provider = new this(ctx);
const {
window: { registerTreeDataProvider },
commands: { registerCommand, executeCommand }
} = vscode;
ctx.subscriptions.push(
registerTreeDataProvider('go.explorer', provider),
registerCommand('go.explorer.refresh', () => provider.update(true)),
registerCommand('go.explorer.open', (item) => provider.open(item)),
registerCommand('go.workspace.editEnv', (item) => provider.editEnv(item)),
registerCommand('go.workspace.resetEnv', (item) => provider.resetEnv(item))
);
executeCommand('setContext', 'go.showExplorer', true);
return provider;
}
private _onDidChangeTreeData = new vscode.EventEmitter<vscode.TreeItem | void>();
readonly onDidChangeTreeData = this._onDidChangeTreeData.event;
constructor(ctx: vscode.ExtensionContext) {
this.update();
ctx.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(() => this.update()),
vscode.workspace.onDidChangeWorkspaceFolders(() => this.update()),
vscode.workspace.onDidChangeConfiguration(() => this.update(true)),
vscode.workspace.onDidCloseTextDocument((doc) => {
if (!this.activeFolder) {
this.goEnvCache.delete(vscodeUri.Utils.dirname(doc.uri).toString());
}
})
);
}
getTreeItem(element: vscode.TreeItem) {
return element;
}
getChildren(element?: vscode.TreeItem) {
if (!element) {
return [this.envTree(), this.toolTree()];
}
if (isEnvTree(element)) {
return this.envTreeItems(element.workspace);
}
if (isToolTree(element)) {
return this.toolTreeItems();
}
if (isToolTreeItem(element)) {
return element.children;
}
}
private update(clearCache = false) {
if (clearCache) {
this.goEnvCache.clear();
this.toolDetailCache.clear();
}
const { activeTextEditor } = vscode.window;
const { getWorkspaceFolder, workspaceFolders } = vscode.workspace;
this.activeDocument = activeTextEditor?.document;
this.activeFolder = activeTextEditor?.document
? getWorkspaceFolder(activeTextEditor.document.uri) || workspaceFolders?.[0]
: workspaceFolders?.[0];
this._onDidChangeTreeData.fire();
}
private async open(item: EnvTreeItem) {
if (typeof item.file === 'undefined') return;
const edit = new vscode.WorkspaceEdit();
edit.createFile(item.file, { ignoreIfExists: true });
await vscode.workspace.applyEdit(edit);
const doc = await vscode.workspace.openTextDocument(item.file);
await vscode.window.showTextDocument(doc);
}
private async editEnv(item?: EnvTreeItem) {
const uri = this.activeFolder?.uri;
if (!uri) {
return;
}
let pick: { label?: string; description?: string } | undefined;
if (isEnvTreeItem(item)) {
pick = { label: item.key, description: item.value };
} else {
const items = Object.entries<string>(await runGoEnv(uri))
.filter(([label]) => !GoEnv.readonlyVars.has(label))
.map(([label, description]) => ({
label,
description
}));
pick = await vscode.window.showQuickPick(items, { title: 'Go: Edit Workspace Env' });
}
if (!pick) return;
const { label, description } = pick;
const value = await vscode.window.showInputBox({ title: label, value: description });
if (label && typeof value !== 'undefined') {
await GoEnv.edit({ [label]: value });
}
}
private async resetEnv(item?: EnvTreeItem) {
if (item?.key) {
await GoEnv.reset([item.key]);
return;
}
await GoEnv.reset();
}
private envTree() {
if (this.activeFolder) {
const { name, uri } = this.activeFolder;
return new EnvTree(name, uri);
}
if (this.activeDocument) {
const { fileName, uri } = this.activeDocument;
return new EnvTree(path.basename(fileName), vscodeUri.Utils.dirname(uri));
}
return new EnvTree();
}
private async envTreeItems(uri?: vscode.Uri) {
const env = await this.goEnvCache.get(uri?.toString() ?? '');
const items = [];
for (const [k, v] of Object.entries(env)) {
if (v !== '') {
items.push(new EnvTreeItem(k, v));
}
}
return items;
}
private toolTree() {
return new ToolTree();
}
private async toolTreeItems() {
const allTools = getConfiguredTools(getGoConfig(), getGoplsConfig());
const toolsInfo = await Promise.all(allTools.map((tool) => this.toolDetailCache.get(tool.name)));
const items = [];
for (const t of toolsInfo) {
items.push(new ToolTreeItem(t));
}
return items;
}
}
class EnvTree implements vscode.TreeItem {
label = 'env';
contextValue = 'go:explorer:envtree';
collapsibleState = vscode.TreeItemCollapsibleState.Expanded;
iconPath = new vscode.ThemeIcon('symbol-folder');
constructor(public description = '', public workspace?: vscode.Uri) {}
}
function isEnvTree(item?: vscode.TreeItem): item is EnvTree {
return item?.contextValue === 'go:explorer:envtree';
}
class EnvTreeItem implements vscode.TreeItem {
file?: vscode.Uri;
label: string;
contextValue?: string;
tooltip?: string;
constructor(public key: string, public value: string) {
this.label = `${key}=${replaceHome(value)}`;
this.contextValue = 'go:explorer:envitem';
if (GoEnv.fileVars.has(key)) {
this.contextValue = 'go:explorer:envfile';
this.file = vscode.Uri.file(value);
}
this.tooltip = `${key}=${value}`;
}
}
function isEnvTreeItem(item?: vscode.TreeItem): item is EnvTreeItem {
return item?.contextValue === 'go:explorer:envitem';
}
class GoEnv {
/**
* get returns a subset of go env vars, the union of this.vars and values
* set with toolsEnvVars in the go workspace config.
* @param uri the directory from which to run go env.
* @returns the output of running go env -json VAR1 VAR2...
*/
static async get(uri?: vscode.Uri) {
const toolsEnv = await getGoConfig(uri)['toolsEnvVars'];
const output = await runGoEnv(uri, [...this.vars, ...Object.keys(toolsEnv)]);
return output as Record<string, string>;
}
/**
* update writes to toolsEnvVars in the go workspace config.
* @param vars a record of env vars to update.
*/
static async edit(vars: Record<string, string>) {
const config = getGoConfig();
await config.update('toolsEnvVars', { ...config['toolsEnvVars'], ...vars });
}
/**
* reset removes entries from toolsEnvVars in the go workspace config.
* @param vars env vars to reset.
*/
static async reset(vars?: string[]) {
const config = getGoConfig();
let env: Record<string, string> = {};
if (vars) {
env = { ...config['toolsEnvVars'] };
for (const v of vars) {
delete env[v];
}
}
await config.update('toolsEnvVars', env);
}
/** Vars that point to files. */
static fileVars = new Set(['GOMOD', 'GOWORK', 'GOENV']);
/** Vars available from 'go env' but not read from the environment */
static readonlyVars = new Set([
'GOEXE',
'GOGCCFLAGS',
'GOHOSTARCH',
'GOHOSTOS',
'GOMOD',
'GOTOOLDIR',
'GOVERSION',
'GOWORK'
]);
/** Vars that should always be visible if they contain a value. */
private static vars = ['GOPRIVATE', 'GOMOD', 'GOWORK', 'GOENV', 'GOTOOLCHAIN'];
}
class ToolTree implements vscode.TreeItem {
label = 'tools';
contextValue = 'go:explorer:tools';
collapsibleState = vscode.TreeItemCollapsibleState.Collapsed;
iconPath = new vscode.ThemeIcon('tools');
}
function isToolTree(item?: vscode.TreeItem): item is ToolTree {
return item?.contextValue === 'go:explorer:tools';
}
class ToolTreeItem implements vscode.TreeItem {
contextValue = 'go:explorer:toolitem';
description = 'not installed';
label: string;
children?: vscode.TreeItem[];
collapsibleState?: vscode.TreeItemCollapsibleState;
tooltip?: string;
constructor({ name, version, goVersion, binPath, error }: ToolDetail) {
this.label = name;
if (binPath) {
this.label = `${name}@${version}`;
this.description = `${replaceHome(binPath)} ${goVersion}`;
this.tooltip = `${this.label} ${this.description}`;
}
if (error) {
const msg = `go version -m failed: ${error}`;
this.description = msg;
this.tooltip = msg;
}
}
}
function isToolTreeItem(item?: vscode.TreeItem): item is ToolTreeItem {
return item?.contextValue === 'go:explorer:toolitem';
}
interface ToolDetail {
name: string;
goVersion?: string;
version?: string;
binPath?: string;
error?: Error;
}
async function getToolDetail(name: string): Promise<ToolDetail> {
const toolPath = getBinPath(name);
if (!path.isAbsolute(toolPath)) {
return { name: name };
}
try {
const { goVersion, moduleVersion } = await inspectGoToolVersion(toolPath);
return {
name: name,
binPath: toolPath,
goVersion: goVersion,
version: moduleVersion
};
} catch (e) {
return { name: name, error: e as Error };
}
}
const enum Time {
SECOND = 1000,
MINUTE = SECOND * 60,
HOUR = MINUTE * 60
}
interface CacheEntry<T> {
entry: T;
updatedAt: number;
}
class Cache<T> {
private cache = new Map<string, CacheEntry<T>>();
constructor(private fn: (key: string) => Promise<T>, private ttl: number) {}
async get(key: string, ttl = this.ttl) {
const cache = this.cache.get(key);
const useCache = cache && Date.now() - cache.updatedAt < ttl;
if (useCache) {
return cache.entry;
}
const entry = await this.fn(key);
this.cache.set(key, { entry, updatedAt: Date.now() });
return entry;
}
clear() {
return this.cache.clear();
}
delete(key: string) {
return this.cache.delete(key);
}
}
/**
* replaceHome replaces the home directory prefix of a string with `~`.
* @param maybePath a string that might be a file system path.
* @returns the string with os.homedir() replaced by `~`.
*/
function replaceHome(maybePath: string) {
return maybePath.replace(new RegExp(`^${os.homedir()}`), '~');
}
| vscode-go/extension/src/goExplorer.ts/0 | {
"file_path": "vscode-go/extension/src/goExplorer.ts",
"repo_id": "vscode-go",
"token_count": 3945
} | 784 |
/* eslint-disable @typescript-eslint/no-explicit-any */
/*---------------------------------------------------------
* Copyright 2021 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import vscode = require('vscode');
import { CommandFactory } from './commands';
import { getGoConfig } from './config';
import { extensionId } from './const';
import { GoExtensionContext } from './context';
import {
developerSurveyConfig,
getDeveloperSurveyConfig,
maybePromptForDeveloperSurvey,
promptForDeveloperSurvey
} from './goDeveloperSurvey';
import { outputChannel } from './goStatus';
import { getLocalGoplsVersion } from './language/goLanguageServer';
import { getFromGlobalState, getFromWorkspaceState, updateGlobalState } from './stateUtils';
import { getGoVersion } from './util';
import { promptNext4Weeks } from './utils/randomDayutils';
// GoplsSurveyConfig is the set of global properties used to determine if
// we should prompt a user to take the gopls survey.
export interface GoplsSurveyConfig {
// prompt is true if the user can be prompted to take the survey.
// It is false if the user has responded "Never" to the prompt.
prompt?: boolean;
// promptThisMonth is true if we have used a random number generator
// to determine if the user should be prompted this month.
// It is undefined if we have not yet made the determination.
promptThisMonth?: boolean;
// dateToPromptThisMonth is the date on which we should prompt the user
// this month. (It is no longer necessarily in the current month.)
dateToPromptThisMonth?: Date;
// dateComputedPromptThisMonth is the date on which the values of
// promptThisMonth and dateToPromptThisMonth were set.
dateComputedPromptThisMonth?: Date;
// lastDatePrompted is the most recent date that the user has been prompted.
lastDatePrompted?: Date;
// lastDateAccepted is the most recent date that the user responded "Yes"
// to the survey prompt. The user need not have completed the survey.
lastDateAccepted?: Date;
}
export function maybePromptForGoplsSurvey(goCtx: GoExtensionContext) {
// First, check the value of the 'go.survey.prompt' setting to see
// if the user has opted out of all survey prompts.
const goConfig = getGoConfig();
if (goConfig.get('survey.prompt') === false) {
return;
}
const now = new Date();
let cfg = shouldPromptForSurvey(now, getGoplsSurveyConfig());
if (!cfg) {
return;
}
if (!cfg.dateToPromptThisMonth) {
return;
}
const callback = async () => {
const currentTime = new Date();
const { lastUserAction = new Date() } = goCtx;
// Make sure the user has been idle for at least a minute.
if (minutesBetween(lastUserAction, currentTime) < 1) {
setTimeout(callback, 5 * timeMinute);
return;
}
cfg = await promptForGoplsSurvey(goCtx, cfg, now);
if (cfg) {
flushSurveyConfig(goplsSurveyConfig, cfg);
}
};
// 0 if we passed the computed dateToPromptThisMonth past.
// If the prompt date was computed a while ago (dateComputedPromptThisMonth),
// shouldPromptForSurvey should've made a new decision before we get here.
const delayMs = Math.max(cfg.dateToPromptThisMonth.getTime() - now.getTime(), 0);
setTimeout(callback, delayMs);
}
export function shouldPromptForSurvey(now: Date, cfg: GoplsSurveyConfig): GoplsSurveyConfig | undefined {
// If the prompt value is not set, assume we haven't prompted the user
// and should do so.
if (cfg.prompt === undefined) {
cfg.prompt = true;
}
flushSurveyConfig(goplsSurveyConfig, cfg);
if (!cfg.prompt) {
return;
}
// Check if the user has taken the survey in the last year.
// Don't prompt them if they have been.
if (cfg.lastDateAccepted) {
if (daysBetween(now, cfg.lastDateAccepted) < 365) {
return;
}
}
// Check if the user has been prompted for the survey in the last 90 days.
// Don't prompt them if they have been.
if (cfg.lastDatePrompted) {
if (daysBetween(now, cfg.lastDatePrompted) < 90) {
return;
}
}
// Check if the extension has been activated this month.
if (cfg.dateComputedPromptThisMonth) {
// The extension has been activated this month, so we should have already
// decided if the user should be prompted.
if (daysBetween(now, cfg.dateComputedPromptThisMonth) < 28) {
return cfg;
}
}
// This is the first activation this month (or ever), so decide if we
// should prompt the user. This is done by generating a random number in
// the range [0, 1) and checking if it is < probability.
// We then randomly pick a day in the next 4 weeks to prompt the user.
// Probability is set based on the # of responses received, and will be
// decreased if we begin receiving > 200 responses/month.
const probability = 0.06;
cfg.promptThisMonth = Math.random() < probability;
if (cfg.promptThisMonth) {
cfg.dateToPromptThisMonth = promptNext4Weeks(now);
} else {
cfg.dateToPromptThisMonth = undefined;
}
cfg.dateComputedPromptThisMonth = now;
flushSurveyConfig(goplsSurveyConfig, cfg);
return cfg;
}
async function promptForGoplsSurvey(
goCtx: GoExtensionContext,
cfg: GoplsSurveyConfig = {},
now: Date
): Promise<GoplsSurveyConfig> {
const selected = await vscode.window.showInformationMessage(
`Looks like you are using the Go extension for VS Code.
Could you help us improve this extension by filling out a 1-2 minute survey about your experience with it?`,
'Yes',
'Not now',
'Never'
);
// Update the time last asked.
cfg.lastDatePrompted = now;
switch (selected) {
case 'Yes':
{
const { latestConfig } = goCtx;
cfg.lastDateAccepted = now;
cfg.prompt = true;
const goplsEnabled = latestConfig?.enabled;
const usersGoplsVersion = await getLocalGoplsVersion(latestConfig);
const goV = await getGoVersion();
const goVersion = goV ? (goV.isDevel ? 'devel' : goV.format(true)) : 'na';
const surveyURL = `https://go.dev/s/ide-hats-survey/?s=c&usingGopls=${goplsEnabled}&gopls=${usersGoplsVersion?.version}&extid=${extensionId}&go=${goVersion}&os=${process.platform}`;
await vscode.env.openExternal(vscode.Uri.parse(surveyURL));
}
break;
case 'Not now':
cfg.prompt = true;
vscode.window.showInformationMessage("No problem! We'll ask you again another time.");
break;
case 'Never': {
cfg.prompt = false;
const selected = await vscode.window.showInformationMessage(
`No problem! We won't ask again.
To opt-out of all survey prompts, please disable the 'Go > Survey: Prompt' setting.`,
'Open Settings'
);
switch (selected) {
case 'Open Settings':
vscode.commands.executeCommand('workbench.action.openSettings', 'go.survey.prompt');
break;
default:
break;
}
break;
}
default:
// If the user closes the prompt without making a selection, treat it
// like a "Not now" response.
cfg.prompt = true;
break;
}
return cfg;
}
export const goplsSurveyConfig = 'goplsSurveyConfig';
function getGoplsSurveyConfig(): GoplsSurveyConfig {
return getStateConfig(goplsSurveyConfig) as GoplsSurveyConfig;
}
export const resetSurveyConfigs: CommandFactory = () => () => {
flushSurveyConfig(goplsSurveyConfig, null);
flushSurveyConfig(developerSurveyConfig, null);
};
export function flushSurveyConfig(key: string, cfg: any) {
if (cfg) {
updateGlobalState(key, JSON.stringify(cfg));
} else {
updateGlobalState(key, null); // reset
}
}
export function getStateConfig(globalStateKey: string, workspace?: boolean): any {
let saved: any;
if (workspace === true) {
saved = getFromWorkspaceState(globalStateKey);
} else {
saved = getFromGlobalState(globalStateKey);
}
if (saved === undefined) {
return {};
}
try {
const cfg = JSON.parse(saved, (key: string, value: any) => {
// Make sure values that should be dates are correctly converted.
if (key.toLowerCase().includes('date') || key.toLowerCase().includes('timestamp')) {
return new Date(value);
}
return value;
});
return cfg || {};
} catch (err) {
console.log(`Error parsing JSON from ${saved}: ${err}`);
return {};
}
}
export const showSurveyConfig: CommandFactory = (ctx, goCtx) => async () => {
// TODO(rstambler): Add developer survey config.
outputChannel.appendLine('HaTs Survey Configuration');
outputChannel.appendLine(JSON.stringify(getGoplsSurveyConfig(), null, 2));
outputChannel.show();
outputChannel.appendLine('Developer Survey Configuration');
outputChannel.appendLine(JSON.stringify(getDeveloperSurveyConfig(), null, 2));
outputChannel.show();
let selected = await vscode.window.showInformationMessage('Prompt for HaTS survey?', 'Yes', 'Maybe', 'No');
switch (selected) {
case 'Yes':
promptForGoplsSurvey(goCtx, getGoplsSurveyConfig(), new Date());
break;
case 'Maybe':
maybePromptForGoplsSurvey(goCtx);
break;
default:
break;
}
selected = await vscode.window.showInformationMessage('Prompt for Developer survey?', 'Yes', 'Maybe', 'No');
switch (selected) {
case 'Yes':
promptForDeveloperSurvey(getDeveloperSurveyConfig(), new Date());
break;
case 'Maybe':
maybePromptForDeveloperSurvey(goCtx);
break;
default:
break;
}
};
export const timeMinute = 1000 * 60;
const timeHour = timeMinute * 60;
export const timeDay = timeHour * 24;
// daysBetween returns the number of days between a and b.
export function daysBetween(a: Date, b: Date): number {
return msBetween(a, b) / timeDay;
}
// minutesBetween returns the number of minutes between a and b.
export function minutesBetween(a: Date, b: Date): number {
return msBetween(a, b) / timeMinute;
}
export function msBetween(a: Date, b: Date): number {
return Math.abs(a.getTime() - b.getTime());
}
| vscode-go/extension/src/goSurvey.ts/0 | {
"file_path": "vscode-go/extension/src/goSurvey.ts",
"repo_id": "vscode-go",
"token_count": 3264
} | 785 |
/* eslint-disable @typescript-eslint/no-explicit-any */
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Modification copyright 2020 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import cp = require('child_process');
import fs = require('fs');
import moment = require('moment');
import path = require('path');
import semver = require('semver');
import util = require('util');
import vscode = require('vscode');
import {
CancellationToken,
CloseAction,
ConfigurationParams,
ConfigurationRequest,
ErrorAction,
ExecuteCommandParams,
ExecuteCommandRequest,
ExecuteCommandSignature,
HandleDiagnosticsSignature,
InitializeError,
InitializeResult,
LanguageClientOptions,
Message,
ProgressToken,
ProvideCodeLensesSignature,
ProvideCompletionItemsSignature,
ProvideDocumentFormattingEditsSignature,
ResponseError,
RevealOutputChannelOn
} from 'vscode-languageclient';
import { LanguageClient, ServerOptions } from 'vscode-languageclient/node';
import { getGoConfig, getGoplsConfig, extensionInfo } from '../config';
import { toolExecutionEnvironment } from '../goEnv';
import { GoDocumentFormattingEditProvider, usingCustomFormatTool } from './legacy/goFormat';
import { installTools, latestToolVersion, promptForMissingTool, promptForUpdatingTool } from '../goInstallTools';
import { getTool, Tool } from '../goTools';
import { getFromGlobalState, updateGlobalState, updateWorkspaceState } from '../stateUtils';
import {
getBinPath,
getCheckForToolsUpdatesConfig,
getCurrentGoPath,
getGoVersion,
getWorkspaceFolderPath,
removeDuplicateDiagnostics
} from '../util';
import { getToolFromToolPath } from '../utils/pathUtils';
import fetch from 'node-fetch';
import { CompletionItemKind, FoldingContext } from 'vscode';
import { ProvideFoldingRangeSignature } from 'vscode-languageclient/lib/common/foldingRange';
import { daysBetween, getStateConfig, maybePromptForGoplsSurvey, timeDay, timeMinute } from '../goSurvey';
import { maybePromptForDeveloperSurvey } from '../goDeveloperSurvey';
import { CommandFactory } from '../commands';
import { updateLanguageServerIconGoStatusBar } from '../goStatus';
import { URI } from 'vscode-uri';
import { IVulncheckTerminal, VulncheckReport, VulncheckTerminal, writeVulns } from '../goVulncheck';
import { createHash } from 'crypto';
import { GoExtensionContext } from '../context';
import { GoDocumentSelector } from '../goMode';
export interface LanguageServerConfig {
serverName: string;
path: string;
version?: { version: string; goVersion?: string };
modtime?: Date;
enabled: boolean;
flags: string[];
env: any;
features: {
formatter?: GoDocumentFormattingEditProvider;
};
checkForUpdates: string;
}
export interface ServerInfo {
Name: string;
Version?: string;
GoVersion?: string;
Commands?: string[];
}
export function updateRestartHistory(goCtx: GoExtensionContext, reason: RestartReason, enabled: boolean) {
// Keep the history limited to 10 elements.
goCtx.restartHistory = goCtx.restartHistory ?? [];
while (goCtx.restartHistory.length > 10) {
goCtx.restartHistory = goCtx.restartHistory.slice(1);
}
goCtx.restartHistory.push(new Restart(reason, new Date(), enabled));
}
function formatRestartHistory(goCtx: GoExtensionContext): string {
const result: string[] = [];
for (const restart of goCtx.restartHistory ?? []) {
result.push(`${restart.timestamp.toUTCString()}: ${restart.reason} (enabled: ${restart.enabled})`);
}
return result.join('\n');
}
export enum RestartReason {
ACTIVATION = 'activation',
MANUAL = 'manual',
CONFIG_CHANGE = 'config change',
INSTALLATION = 'installation'
}
export class Restart {
reason: RestartReason;
timestamp: Date;
enabled: boolean;
constructor(reason: RestartReason, timestamp: Date, enabled: boolean) {
this.reason = reason;
this.timestamp = timestamp;
this.enabled = enabled;
}
}
// computes a bigint fingerprint of the machine id.
function hashMachineID(salt?: string): number {
const hash = createHash('md5').update(`${vscode.env.machineId}${salt}`).digest('hex');
return parseInt(hash.substring(0, 8), 16);
}
// returns true if the proposed upgrade version is mature, or we are selected for staged rollout.
export async function okForStagedRollout(
tool: Tool,
ver: semver.SemVer,
hashFn: (key?: string) => number
): Promise<boolean> {
// patch release is relatively safe to upgrade. Moreover, the patch
// can carry a fix for security which is better to apply sooner.
if (ver.patch !== 0 || ver.prerelease?.length > 0) return true;
const published = await getTimestampForVersion(tool, ver);
if (!published) return true;
const days = daysBetween(new Date(), published.toDate());
if (days <= 1) {
return hashFn(ver.version) % 100 < 10; // upgrade with 10% chance for the first day.
}
if (days <= 3) {
return hashFn(ver.version) % 100 < 30; // upgrade with 30% chance for the first 3 days.
}
return true;
}
// scheduleGoplsSuggestions sets timeouts for the various gopls-specific
// suggestions. We check user's gopls versions once per day to prompt users to
// update to the latest version. We also check if we should prompt users to
// fill out the survey.
export function scheduleGoplsSuggestions(goCtx: GoExtensionContext) {
if (extensionInfo.isInCloudIDE) {
return;
}
// Some helper functions.
const usingGo = (): boolean => {
return vscode.workspace.textDocuments.some((doc) => doc.languageId === 'go');
};
const installGopls = async (cfg: LanguageServerConfig) => {
const tool = getTool('gopls');
const versionToUpdate = await shouldUpdateLanguageServer(tool, cfg);
if (!versionToUpdate) {
return;
}
// If the user has opted in to automatic tool updates, we can update
// without prompting.
const toolsManagementConfig = getGoConfig()['toolsManagement'];
if (toolsManagementConfig && toolsManagementConfig['autoUpdate'] === true) {
if (extensionInfo.isPreview || (await okForStagedRollout(tool, versionToUpdate, hashMachineID))) {
const goVersion = await getGoVersion();
const toolVersion = { ...tool, version: versionToUpdate }; // ToolWithVersion
await installTools([toolVersion], goVersion, { silent: true });
} else {
console.log(`gopls ${versionToUpdate} is too new, try to update later`);
}
} else {
promptForUpdatingTool(tool.name, versionToUpdate);
}
};
const update = async () => {
setTimeout(update, timeDay);
const cfg = goCtx.latestConfig;
// trigger periodic update check only if the user is already using gopls.
// Otherwise, let's check again tomorrow.
if (!cfg || !cfg.enabled || cfg.serverName !== 'gopls') {
return;
}
await installGopls(cfg);
};
const survey = async () => {
setTimeout(survey, timeDay);
// Only prompt for the survey if the user is working on Go code.
if (!usingGo) {
return;
}
maybePromptForGoplsSurvey(goCtx);
maybePromptForDeveloperSurvey(goCtx);
};
const telemetry = () => {
if (!usingGo) {
return;
}
maybePromptForTelemetry(goCtx);
};
setTimeout(update, 10 * timeMinute);
setTimeout(survey, 30 * timeMinute);
setTimeout(telemetry, 6 * timeMinute);
}
// Ask users to fill out opt-out survey.
export async function promptAboutGoplsOptOut(goCtx: GoExtensionContext) {
// Check if the configuration is set in the workspace.
const useLanguageServer = getGoConfig().inspect('useLanguageServer');
const workspace = useLanguageServer?.workspaceFolderValue === false || useLanguageServer?.workspaceValue === false;
let cfg = getGoplsOptOutConfig(workspace);
const promptFn = async (): Promise<GoplsOptOutConfig> => {
if (cfg.prompt === false) {
return cfg;
}
// Prompt the user ~once a month.
if (cfg.lastDatePrompted && daysBetween(new Date(), cfg.lastDatePrompted) < 30) {
return cfg;
}
cfg.lastDatePrompted = new Date();
await promptForGoplsOptOutSurvey(
goCtx,
cfg,
"It looks like you've disabled the Go language server. Would you be willing to tell us why you've disabled it, so that we can improve it?"
);
return cfg;
};
cfg = await promptFn();
flushGoplsOptOutConfig(cfg, workspace);
}
async function promptForGoplsOptOutSurvey(
goCtx: GoExtensionContext,
cfg: GoplsOptOutConfig,
msg: string
): Promise<GoplsOptOutConfig> {
const s = await vscode.window.showInformationMessage(msg, { title: 'Yes' }, { title: 'No' });
if (!s) {
return cfg;
}
const localGoplsVersion = await getLocalGoplsVersion(goCtx.latestConfig);
const goplsVersion = localGoplsVersion?.version || 'na';
const goV = await getGoVersion();
let goVersion = 'na';
if (goV) {
goVersion = goV.format(true);
}
switch (s.title) {
case 'Yes':
cfg.prompt = false;
await vscode.env.openExternal(
vscode.Uri.parse(
`https://google.qualtrics.com/jfe/form/SV_doId0RNgV3pHovc?gopls=${goplsVersion}&go=${goVersion}&os=${process.platform}`
)
);
break;
case 'No':
break;
}
return cfg;
}
export interface GoplsOptOutConfig {
prompt?: boolean;
lastDatePrompted?: Date;
}
const goplsOptOutConfigKey = 'goplsOptOutConfig';
export const getGoplsOptOutConfig = (workspace: boolean): GoplsOptOutConfig => {
return getStateConfig(goplsOptOutConfigKey, workspace) as GoplsOptOutConfig;
};
export const flushGoplsOptOutConfig = (cfg: GoplsOptOutConfig, workspace: boolean) => {
if (workspace) {
updateWorkspaceState(goplsOptOutConfigKey, JSON.stringify(cfg));
}
updateGlobalState(goplsOptOutConfigKey, JSON.stringify(cfg));
};
// exported for testing.
export async function stopLanguageClient(goCtx: GoExtensionContext) {
const c = goCtx.languageClient;
goCtx.crashCount = 0;
goCtx.telemetryService = undefined;
goCtx.languageClient = undefined;
if (!c) return false;
if (c.diagnostics) {
c.diagnostics.clear();
}
// LanguageClient.stop may hang if the language server
// crashes during shutdown before responding to the
// shutdown request. Enforce client-side timeout.
try {
c.stop(2000);
} catch (e) {
c.outputChannel?.appendLine(`Failed to stop client: ${e}`);
}
}
export function toServerInfo(res?: InitializeResult): ServerInfo | undefined {
if (!res) return undefined;
const info: ServerInfo = {
Commands: res.capabilities?.executeCommandProvider?.commands || [],
Name: res.serverInfo?.name || 'unknown'
};
try {
interface serverVersionJSON {
GoVersion?: string;
Version?: string;
// before gopls 0.8.0
version?: string;
}
const v = <serverVersionJSON>(res.serverInfo?.version ? JSON.parse(res.serverInfo.version) : {});
info.Version = v.Version || v.version;
info.GoVersion = v.GoVersion;
} catch (e) {
// gopls is not providing any info, that's ok.
}
return info;
}
export interface BuildLanguageClientOption extends LanguageServerConfig {
outputChannel?: vscode.OutputChannel;
traceOutputChannel?: vscode.OutputChannel;
}
// buildLanguageClientOption returns the default, extra configuration
// used in building a new LanguageClient instance. Options specified
// in LanguageServerConfig
export function buildLanguageClientOption(
goCtx: GoExtensionContext,
cfg: LanguageServerConfig
): BuildLanguageClientOption {
// Reuse the same output channel for each instance of the server.
if (cfg.enabled) {
if (!goCtx.serverOutputChannel) {
goCtx.serverOutputChannel = vscode.window.createOutputChannel(cfg.serverName + ' (server)');
}
if (!goCtx.serverTraceChannel) {
goCtx.serverTraceChannel = vscode.window.createOutputChannel(cfg.serverName);
}
}
return Object.assign(
{
outputChannel: goCtx.serverOutputChannel,
traceOutputChannel: goCtx.serverTraceChannel
},
cfg
);
}
export class GoLanguageClient extends LanguageClient implements vscode.Disposable {
constructor(
id: string,
name: string,
serverOptions: ServerOptions,
clientOptions: LanguageClientOptions,
private onDidChangeVulncheckResultEmitter: vscode.EventEmitter<VulncheckEvent>
) {
super(id, name, serverOptions, clientOptions);
}
dispose(timeout?: number) {
this.onDidChangeVulncheckResultEmitter.dispose();
return super.dispose(timeout);
}
public get onDidChangeVulncheckResult(): vscode.Event<VulncheckEvent> {
return this.onDidChangeVulncheckResultEmitter.event;
}
}
type VulncheckEvent = {
URI?: URI;
message?: string;
};
// buildLanguageClient returns a language client built using the given language server config.
// The returned language client need to be started before use.
export async function buildLanguageClient(
goCtx: GoExtensionContext,
cfg: BuildLanguageClientOption
): Promise<GoLanguageClient> {
await getLocalGoplsVersion(cfg); // populate and cache cfg.version
const goplsWorkspaceConfig = await adjustGoplsWorkspaceConfiguration(cfg, getGoplsConfig(), 'gopls', undefined);
// when initialization is failed after the connection is established,
// we want to handle the connection close error case specially. Capture the error
// in initializationFailedHandler and handle it in the connectionCloseHandler.
let initializationError: ResponseError<InitializeError> | undefined = undefined;
let govulncheckTerminal: IVulncheckTerminal | undefined;
const pendingVulncheckProgressToken = new Map<ProgressToken, any>();
const onDidChangeVulncheckResultEmitter = new vscode.EventEmitter<VulncheckEvent>();
// cfg is captured by closures for later use during error report.
const c = new GoLanguageClient(
'go', // id
cfg.serverName, // name e.g. gopls
{
command: cfg.path,
args: ['-mode=stdio', ...cfg.flags],
options: { env: cfg.env }
} as ServerOptions,
{
initializationOptions: goplsWorkspaceConfig,
documentSelector: GoDocumentSelector,
uriConverters: {
// Apply file:/// scheme to all file paths.
code2Protocol: (uri: vscode.Uri): string =>
(uri.scheme ? uri : uri.with({ scheme: 'file' })).toString(),
protocol2Code: (uri: string) => vscode.Uri.parse(uri)
},
outputChannel: cfg.outputChannel,
traceOutputChannel: cfg.traceOutputChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
initializationFailedHandler: (error: ResponseError<InitializeError>): boolean => {
initializationError = error;
return false;
},
errorHandler: {
error: (error: Error, message: Message, count: number) => {
// Allow 5 crashes before shutdown.
if (count < 5) {
return {
message: '', // suppresses error popups
action: ErrorAction.Continue
};
}
return {
message: '', // suppresses error popups
action: ErrorAction.Shutdown
};
},
closed: () => {
if (initializationError !== undefined) {
suggestGoplsIssueReport(
goCtx,
cfg,
'The gopls server failed to initialize.',
errorKind.initializationFailure,
initializationError
);
initializationError = undefined;
// In case of initialization failure, do not try to restart.
return {
message: '', // suppresses error popups - there will be other popups. :-(
action: CloseAction.DoNotRestart
};
}
// Allow 5 crashes before shutdown.
const { crashCount = 0 } = goCtx;
goCtx.crashCount = crashCount + 1;
if (goCtx.crashCount < 5) {
updateLanguageServerIconGoStatusBar(c, true);
return {
message: '', // suppresses error popups
action: CloseAction.Restart
};
}
suggestGoplsIssueReport(
goCtx,
cfg,
'The connection to gopls has been closed. The gopls server may have crashed.',
errorKind.crash
);
updateLanguageServerIconGoStatusBar(c, true);
return {
message: '', // suppresses error popups - there will be other popups.
action: CloseAction.DoNotRestart
};
}
},
middleware: {
handleWorkDoneProgress: async (token, params, next) => {
switch (params.kind) {
case 'begin':
break;
case 'report':
if (pendingVulncheckProgressToken.has(token) && params.message) {
govulncheckTerminal?.appendLine(params.message);
}
break;
case 'end':
if (pendingVulncheckProgressToken.has(token)) {
const out = pendingVulncheckProgressToken.get(token);
pendingVulncheckProgressToken.delete(token);
// success. In case of failure, it will be 'failed'
onDidChangeVulncheckResultEmitter.fire({ URI: out.URI, message: params.message });
}
}
next(token, params);
},
executeCommand: async (command: string, args: any[], next: ExecuteCommandSignature) => {
try {
if (command === 'gopls.tidy') {
await vscode.workspace.saveAll(false);
}
if (command === 'gopls.run_govulncheck' && args.length && args[0].URI) {
if (govulncheckTerminal) {
vscode.window.showErrorMessage(
'cannot start vulncheck while another vulncheck is in progress'
);
return;
}
await vscode.workspace.saveAll(false);
const uri = args[0].URI ? URI.parse(args[0].URI) : undefined;
const dir = uri?.fsPath?.endsWith('.mod') ? path.dirname(uri.fsPath) : uri?.fsPath;
govulncheckTerminal = VulncheckTerminal.Open();
govulncheckTerminal.appendLine(`⚡ govulncheck -C ${dir} ./...\n\n`);
govulncheckTerminal.show();
}
const res = await next(command, args);
if (command === 'gopls.run_govulncheck') {
const progressToken = res.Token;
if (progressToken) {
pendingVulncheckProgressToken.set(progressToken, args[0]);
}
}
return res;
} catch (e) {
// TODO: how to print ${e} reliably???
const answer = await vscode.window.showErrorMessage(
`Command '${command}' failed: ${e}.`,
'Show Trace'
);
if (answer === 'Show Trace') {
goCtx.serverOutputChannel?.show();
}
return null;
}
},
provideFoldingRanges: async (
doc: vscode.TextDocument,
context: FoldingContext,
token: CancellationToken,
next: ProvideFoldingRangeSignature
) => {
const ranges = await next(doc, context, token);
if ((!ranges || ranges.length === 0) && doc.lineCount > 0) {
return undefined;
}
return ranges;
},
provideCodeLenses: async (
doc: vscode.TextDocument,
token: vscode.CancellationToken,
next: ProvideCodeLensesSignature
): Promise<vscode.CodeLens[]> => {
const codeLens = await next(doc, token);
if (!codeLens || codeLens.length === 0) {
return codeLens ?? [];
}
return codeLens.reduce((lenses: vscode.CodeLens[], lens: vscode.CodeLens) => {
switch (lens.command?.title) {
case 'run test': {
return [...lenses, ...createTestCodeLens(lens)];
}
case 'run benchmark': {
return [...lenses, ...createBenchmarkCodeLens(lens)];
}
default: {
return [...lenses, lens];
}
}
}, []);
},
provideDocumentFormattingEdits: async (
document: vscode.TextDocument,
options: vscode.FormattingOptions,
token: vscode.CancellationToken,
next: ProvideDocumentFormattingEditsSignature
) => {
if (cfg.features.formatter) {
return cfg.features.formatter.provideDocumentFormattingEdits(document, options, token);
}
return next(document, options, token);
},
handleDiagnostics: (
uri: vscode.Uri,
diagnostics: vscode.Diagnostic[],
next: HandleDiagnosticsSignature
) => {
const { buildDiagnosticCollection, lintDiagnosticCollection, vetDiagnosticCollection } = goCtx;
// Deduplicate diagnostics with those found by the other tools.
removeDuplicateDiagnostics(vetDiagnosticCollection, uri, diagnostics);
removeDuplicateDiagnostics(buildDiagnosticCollection, uri, diagnostics);
removeDuplicateDiagnostics(lintDiagnosticCollection, uri, diagnostics);
return next(uri, diagnostics);
},
provideCompletionItem: async (
document: vscode.TextDocument,
position: vscode.Position,
context: vscode.CompletionContext,
token: vscode.CancellationToken,
next: ProvideCompletionItemsSignature
) => {
const list = await next(document, position, context, token);
if (!list) {
return list;
}
const items = Array.isArray(list) ? list : list.items;
// Give all the candidates the same filterText to trick VSCode
// into not reordering our candidates. All the candidates will
// appear to be equally good matches, so VSCode's fuzzy
// matching/ranking just maintains the natural "sortText"
// ordering. We can only do this in tandem with
// "incompleteResults" since otherwise client side filtering is
// important.
if (!Array.isArray(list) && list.isIncomplete && list.items.length > 1) {
let hardcodedFilterText = items[0].filterText;
if (!hardcodedFilterText) {
// tslint:disable:max-line-length
// According to LSP spec,
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
// if filterText is falsy, the `label` should be used.
// But we observed that's not the case.
// Even if vscode picked the label value, that would
// cause to reorder candiates, which is not ideal.
// Force to use non-empty `label`.
// https://github.com/golang/vscode-go/issues/441
let { label } = items[0];
if (typeof label !== 'string') label = label.label;
hardcodedFilterText = label;
}
for (const item of items) {
item.filterText = hardcodedFilterText;
}
}
const paramHints = vscode.workspace.getConfiguration('editor.parameterHints', {
languageId: 'go',
uri: document.uri
});
// If the user has parameterHints (signature help) enabled,
// trigger it for function or method completion items.
if (paramHints.get<boolean>('enabled') === true) {
for (const item of items) {
if (item.kind === CompletionItemKind.Method || item.kind === CompletionItemKind.Function) {
item.command = {
title: 'triggerParameterHints',
command: 'editor.action.triggerParameterHints'
};
}
}
}
return list;
},
// Keep track of the last file change in order to not prompt
// user if they are actively working.
didOpen: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
didChange: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
didClose: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
didSave: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
workspace: {
configuration: async (
params: ConfigurationParams,
token: CancellationToken,
next: ConfigurationRequest.HandlerSignature
): Promise<any[] | ResponseError<void>> => {
const configs = await next(params, token);
if (!configs || !Array.isArray(configs)) {
return configs;
}
const ret = [] as any[];
for (let i = 0; i < configs.length; i++) {
let workspaceConfig = configs[i];
if (!!workspaceConfig && typeof workspaceConfig === 'object') {
const scopeUri = params.items[i].scopeUri;
const resource = scopeUri ? vscode.Uri.parse(scopeUri) : undefined;
const section = params.items[i].section;
workspaceConfig = await adjustGoplsWorkspaceConfiguration(
cfg,
workspaceConfig,
section,
resource
);
}
ret.push(workspaceConfig);
}
return ret;
}
}
}
} as LanguageClientOptions,
onDidChangeVulncheckResultEmitter
);
onDidChangeVulncheckResultEmitter.event(async (e: VulncheckEvent) => {
if (!govulncheckTerminal) {
return;
}
if (!e || !e.URI) {
govulncheckTerminal.appendLine(`unexpected vulncheck event: ${JSON.stringify(e)}`);
return;
}
try {
if (e.message === 'completed') {
const res = await goplsFetchVulncheckResult(goCtx, e.URI.toString());
if (res!.Vulns) {
vscode.window.showWarningMessage(
'upgrade gopls (v0.14.0 or newer) to see the details about detected vulnerabilities'
);
} else {
await writeVulns(res, govulncheckTerminal, cfg.path);
}
} else {
govulncheckTerminal.appendLine(`terminated without result: ${e.message}`);
}
} catch (e) {
govulncheckTerminal.appendLine(`Fetching govulncheck output from gopls failed ${e}`);
} finally {
govulncheckTerminal.show();
govulncheckTerminal = undefined;
}
});
return c;
}
// filterGoplsDefaultConfigValues removes the entries filled based on the default values
// and selects only those the user explicitly specifies in their settings.
// This returns a new object created based on the filtered properties of workspaceConfig.
// Exported for testing.
export function filterGoplsDefaultConfigValues(workspaceConfig: any, resource?: vscode.Uri): any {
if (!workspaceConfig) {
workspaceConfig = {};
}
const cfg = getGoplsConfig(resource);
const filtered = {} as { [key: string]: any };
for (const [key, value] of Object.entries(workspaceConfig)) {
if (typeof value === 'function') {
continue;
}
const c = cfg.inspect(key);
// select only the field whose current value comes from non-default setting.
if (
!c ||
!util.isDeepStrictEqual(c.defaultValue, value) ||
// c.defaultValue !== value would be most likely sufficient, except
// when gopls' default becomes different from extension's default.
// So, we also forward the key if ever explicitely stated in one of the
// settings layers.
c.globalLanguageValue !== undefined ||
c.globalValue !== undefined ||
c.workspaceFolderLanguageValue !== undefined ||
c.workspaceFolderValue !== undefined ||
c.workspaceLanguageValue !== undefined ||
c.workspaceValue !== undefined
) {
filtered[key] = value;
}
}
return filtered;
}
// passGoConfigToGoplsConfigValues passes some of the relevant 'go.' settings to gopls settings.
// This assumes `goplsWorkspaceConfig` is an output of filterGoplsDefaultConfigValues,
// so it is modifiable and doesn't contain properties that are not explicitly set.
// - go.buildTags and go.buildFlags are passed as gopls.build.buildFlags
// if goplsWorkspaceConfig doesn't explicitly set it yet.
// Exported for testing.
export function passGoConfigToGoplsConfigValues(goplsWorkspaceConfig: any, goWorkspaceConfig: any): any {
if (!goplsWorkspaceConfig) {
goplsWorkspaceConfig = {};
}
const buildFlags = [] as string[];
if (goWorkspaceConfig?.buildFlags) {
buildFlags.push(...goWorkspaceConfig.buildFlags);
}
if (goWorkspaceConfig?.buildTags && buildFlags.indexOf('-tags') === -1) {
buildFlags.push('-tags', goWorkspaceConfig?.buildTags);
}
// If gopls.build.buildFlags is set, don't touch it.
if (buildFlags.length > 0 && goplsWorkspaceConfig['build.buildFlags'] === undefined) {
goplsWorkspaceConfig['build.buildFlags'] = buildFlags;
}
return goplsWorkspaceConfig;
}
// adjustGoplsWorkspaceConfiguration filters unnecessary options and adds any necessary, additional
// options to the gopls config. See filterGoplsDefaultConfigValues, passGoConfigToGoplsConfigValues.
// If this is for the nightly extension, we also request to activate features under experiments.
async function adjustGoplsWorkspaceConfiguration(
cfg: LanguageServerConfig,
workspaceConfig: any,
section?: string,
resource?: vscode.Uri
): Promise<any> {
// We process only gopls config
if (section !== 'gopls') {
return workspaceConfig;
}
workspaceConfig = filterGoplsDefaultConfigValues(workspaceConfig, resource) || {};
// note: workspaceConfig is a modifiable, valid object.
const goConfig = getGoConfig(resource);
workspaceConfig = passGoConfigToGoplsConfigValues(workspaceConfig, goConfig);
workspaceConfig = await passInlayHintConfigToGopls(cfg, workspaceConfig, goConfig);
workspaceConfig = await passVulncheckConfigToGopls(cfg, workspaceConfig, goConfig);
workspaceConfig = await passLinkifyShowMessageToGopls(cfg, workspaceConfig);
// Only modify the user's configurations for the Nightly.
if (!extensionInfo.isPreview) {
return workspaceConfig;
}
if (workspaceConfig && !workspaceConfig['allExperiments']) {
workspaceConfig['allExperiments'] = true;
}
return workspaceConfig;
}
async function passInlayHintConfigToGopls(cfg: LanguageServerConfig, goplsConfig: any, goConfig: any) {
const goplsVersion = await getLocalGoplsVersion(cfg);
if (!goplsVersion) return goplsConfig ?? {};
const version = semver.parse(goplsVersion.version);
if ((version?.compare('0.8.4') ?? 1) > 0) {
const { inlayHints } = goConfig;
if (inlayHints) {
goplsConfig['ui.inlayhint.hints'] = { ...inlayHints };
}
}
return goplsConfig;
}
async function passVulncheckConfigToGopls(cfg: LanguageServerConfig, goplsConfig: any, goConfig: any) {
const goplsVersion = await getLocalGoplsVersion(cfg);
if (!goplsVersion) return goplsConfig ?? {};
const version = semver.parse(goplsVersion.version);
if ((version?.compare('0.10.1') ?? 1) > 0) {
const vulncheck = goConfig.get('diagnostic.vulncheck');
if (vulncheck) {
goplsConfig['ui.vulncheck'] = vulncheck;
}
}
return goplsConfig;
}
async function passLinkifyShowMessageToGopls(cfg: LanguageServerConfig, goplsConfig: any) {
goplsConfig = goplsConfig ?? {};
const goplsVersion = await getLocalGoplsVersion(cfg);
if (!goplsVersion) return goplsConfig;
const version = semver.parse(goplsVersion.version);
// The linkifyShowMessage option was added in v0.14.0-pre.1.
if ((version?.compare('0.13.99') ?? 1) > 0) {
goplsConfig['linkifyShowMessage'] = true;
}
return goplsConfig;
}
// createTestCodeLens adds the go.test.cursor and go.debug.cursor code lens
function createTestCodeLens(lens: vscode.CodeLens): vscode.CodeLens[] {
// CodeLens argument signature in gopls is [fileName: string, testFunctions: string[], benchFunctions: string[]],
// so this needs to be deconstructured here
// Note that there will always only be one test function name in this context
if ((lens.command?.arguments?.length ?? 0) < 2 || (lens.command?.arguments?.[1].length ?? 0) < 1) {
return [lens];
}
return [
new vscode.CodeLens(lens.range, {
title: '',
...lens.command,
command: 'go.test.cursor',
arguments: [{ functionName: lens.command?.arguments?.[1][0] }]
}),
new vscode.CodeLens(lens.range, {
title: 'debug test',
command: 'go.debug.cursor',
arguments: [{ functionName: lens.command?.arguments?.[1][0] }]
})
];
}
function createBenchmarkCodeLens(lens: vscode.CodeLens): vscode.CodeLens[] {
// CodeLens argument signature in gopls is [fileName: string, testFunctions: string[], benchFunctions: string[]],
// so this needs to be deconstructured here
// Note that there will always only be one benchmark function name in this context
if ((lens.command?.arguments?.length ?? 0) < 3 || (lens.command?.arguments?.[2].length ?? 0) < 1) {
return [lens];
}
return [
new vscode.CodeLens(lens.range, {
title: '',
...lens.command,
command: 'go.benchmark.cursor',
arguments: [{ functionName: lens.command?.arguments?.[2][0] }]
}),
new vscode.CodeLens(lens.range, {
title: 'debug benchmark',
command: 'go.debug.cursor',
arguments: [{ functionName: lens.command?.arguments?.[2][0] }]
})
];
}
export async function watchLanguageServerConfiguration(goCtx: GoExtensionContext, e: vscode.ConfigurationChangeEvent) {
if (!e.affectsConfiguration('go')) {
return;
}
if (
e.affectsConfiguration('go.useLanguageServer') ||
e.affectsConfiguration('go.languageServerFlags') ||
e.affectsConfiguration('go.alternateTools') ||
e.affectsConfiguration('go.toolsEnvVars') ||
e.affectsConfiguration('go.formatTool')
// TODO: Should we check http.proxy too? That affects toolExecutionEnvironment too.
) {
vscode.commands.executeCommand('go.languageserver.restart', RestartReason.CONFIG_CHANGE);
}
if (e.affectsConfiguration('go.useLanguageServer') && getGoConfig()['useLanguageServer'] === false) {
promptAboutGoplsOptOut(goCtx);
}
}
export async function buildLanguageServerConfig(
goConfig: vscode.WorkspaceConfiguration
): Promise<LanguageServerConfig> {
let formatter: GoDocumentFormattingEditProvider | undefined;
if (usingCustomFormatTool(goConfig)) {
formatter = new GoDocumentFormattingEditProvider();
}
const cfg: LanguageServerConfig = {
serverName: '', // remain empty if gopls binary can't be found.
path: '',
enabled: goConfig['useLanguageServer'] === true,
flags: goConfig['languageServerFlags'] || [],
features: {
// TODO: We should have configs that match these names.
// Ultimately, we should have a centralized language server config rather than separate fields.
formatter: formatter
},
env: toolExecutionEnvironment(),
checkForUpdates: getCheckForToolsUpdatesConfig(goConfig)
};
// user has opted out of using the language server.
if (!cfg.enabled) {
return cfg;
}
// locate the configured language server tool.
const languageServerPath = getLanguageServerToolPath();
if (!languageServerPath) {
// Assume the getLanguageServerToolPath will show the relevant
// errors to the user. Disable the language server.
cfg.enabled = false;
return cfg;
}
cfg.path = languageServerPath;
cfg.serverName = getToolFromToolPath(cfg.path) ?? '';
// Get the mtime of the language server binary so that we always pick up
// the right version.
const stats = fs.statSync(languageServerPath);
if (!stats) {
vscode.window.showErrorMessage(`Unable to stat path to language server binary: ${languageServerPath}.
Please try reinstalling it.`);
// Disable the language server.
cfg.enabled = false;
return cfg;
}
cfg.modtime = stats.mtime;
cfg.version = await getLocalGoplsVersion(cfg);
return cfg;
}
/**
*
* Return the absolute path to the correct binary. If the required tool is not available,
* prompt the user to install it. Only gopls is officially supported.
*/
export function getLanguageServerToolPath(): string | undefined {
const goConfig = getGoConfig();
// Check that all workspace folders are configured with the same GOPATH.
if (!allFoldersHaveSameGopath()) {
vscode.window.showInformationMessage(
`The Go language server is currently not supported in a multi-root set-up with different GOPATHs (${gopathsPerFolder()}).`
);
return;
}
// Get the path to gopls (getBinPath checks for alternate tools).
const goplsBinaryPath = getBinPath('gopls');
if (path.isAbsolute(goplsBinaryPath)) {
return goplsBinaryPath;
}
const alternateTools = goConfig['alternateTools'];
if (alternateTools) {
// The user's alternate language server was not found.
const goplsAlternate = alternateTools['gopls'];
if (goplsAlternate) {
vscode.window.showErrorMessage(
`Cannot find the alternate tool ${goplsAlternate} configured for gopls.
Please install it and reload this VS Code window.`
);
return;
}
}
// Prompt the user to install gopls.
promptForMissingTool('gopls');
}
function allFoldersHaveSameGopath(): boolean {
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length <= 1) {
return true;
}
const tempGopath = getCurrentGoPath(vscode.workspace.workspaceFolders[0].uri);
return vscode.workspace.workspaceFolders.find((x) => tempGopath !== getCurrentGoPath(x.uri)) ? false : true;
}
function gopathsPerFolder(): string[] {
const result: string[] = [];
for (const folder of vscode.workspace.workspaceFolders ?? []) {
result.push(getCurrentGoPath(folder.uri));
}
return result;
}
export async function shouldUpdateLanguageServer(
tool: Tool,
cfg?: LanguageServerConfig,
mustCheck?: boolean
): Promise<semver.SemVer | null | undefined> {
if (!cfg) {
return null;
}
// Only support updating gopls for now.
if (tool.name !== 'gopls' || (!mustCheck && (cfg.checkForUpdates === 'off' || extensionInfo.isInCloudIDE))) {
return null;
}
if (!cfg.enabled) {
return null;
}
// If the Go version is too old, don't update.
const goVersion = await getGoVersion();
if (!goVersion || (tool.minimumGoVersion && goVersion.lt(tool.minimumGoVersion.format()))) {
return null;
}
// First, run the "gopls version" command and parse its results.
// TODO(rstambler): Confirm that the gopls binary's modtime matches the
// modtime in the config. Update it if needed.
const usersVersion = await getLocalGoplsVersion(cfg);
// We might have a developer version. Don't make the user update.
if (usersVersion && usersVersion.version === '(devel)') {
return null;
}
// Get the latest gopls version. If it is for nightly, using the prereleased version is ok.
let latestVersion =
cfg.checkForUpdates === 'local' ? tool.latestVersion : await latestToolVersion(tool, extensionInfo.isPreview);
// If we failed to get the gopls version, pick the one we know to be latest at the time of this extension's last update
if (!latestVersion) {
latestVersion = tool.latestVersion;
}
// If "gopls" is so old that it doesn't have the "gopls version" command,
// or its version doesn't match our expectations, usersVersion will be empty or invalid.
// Suggest the latestVersion.
if (!usersVersion || !semver.valid(usersVersion.version)) {
return latestVersion;
}
// The user may have downloaded golang.org/x/tools/gopls@master,
// which means that they have a pseudoversion.
const usersTime = parseTimestampFromPseudoversion(usersVersion.version);
// If the user has a pseudoversion, get the timestamp for the latest gopls version and compare.
if (usersTime) {
let latestTime = cfg.checkForUpdates
? await getTimestampForVersion(tool, latestVersion!)
: tool.latestVersionTimestamp;
if (!latestTime) {
latestTime = tool.latestVersionTimestamp;
}
return usersTime.isBefore(latestTime) ? latestVersion : null;
}
// If the user's version does not contain a timestamp,
// default to a semver comparison of the two versions.
const usersVersionSemver = semver.parse(usersVersion.version, {
includePrerelease: true,
loose: true
});
return semver.lt(usersVersionSemver!, latestVersion!) ? latestVersion : null;
}
// Copied from src/cmd/go/internal/modfetch.go.
const pseudoVersionRE = /^v[0-9]+\.(0\.0-|\d+\.\d+-([^+]*\.)?0\.)\d{14}-[A-Za-z0-9]+(\+incompatible)?$/;
// parseTimestampFromPseudoversion returns the timestamp for the given
// pseudoversion. The timestamp is the center component, and it has the
// format "YYYYMMDDHHmmss".
function parseTimestampFromPseudoversion(version: string): moment.Moment | null {
const split = version.split('-');
if (split.length < 2) {
return null;
}
if (!semver.valid(version)) {
return null;
}
if (!pseudoVersionRE.test(version)) {
return null;
}
const sv = semver.coerce(version);
if (!sv) {
return null;
}
// Copied from src/cmd/go/internal/modfetch.go.
const build = sv.build.join('.');
const buildIndex = version.lastIndexOf(build);
if (buildIndex >= 0) {
version = version.substring(0, buildIndex);
}
const lastDashIndex = version.lastIndexOf('-');
version = version.substring(0, lastDashIndex);
const firstDashIndex = version.lastIndexOf('-');
const dotIndex = version.lastIndexOf('.');
let timestamp: string;
if (dotIndex > firstDashIndex) {
// "vX.Y.Z-pre.0" or "vX.Y.(Z+1)-0"
timestamp = version.substring(dotIndex + 1);
} else {
// "vX.0.0"
timestamp = version.substring(firstDashIndex + 1);
}
return moment.utc(timestamp, 'YYYYMMDDHHmmss');
}
export const getTimestampForVersion = async (tool: Tool, version: semver.SemVer) => {
const data = await goProxyRequest(tool, `v${version.format()}.info`);
if (!data) {
return null;
}
const time = moment(data['Time']);
return time;
};
interface GoplsVersionOutput {
GoVersion: string;
Main: {
Path: string;
Version: string;
};
}
// getLocalGoplsVersion returns the version of gopls that is currently
// installed on the user's machine. This is determined by running the
// `gopls version` command.
//
// If this command has already been executed, it returns the saved result.
export const getLocalGoplsVersion = async (cfg?: LanguageServerConfig) => {
if (!cfg) {
return;
}
if (cfg.version) {
return cfg.version;
}
if (cfg.path === '') {
return;
}
const env = toolExecutionEnvironment();
const cwd = getWorkspaceFolderPath();
const execFile = util.promisify(cp.execFile);
try {
const { stdout } = await execFile(cfg.path, ['version', '-json'], { env, cwd });
const v = <GoplsVersionOutput>JSON.parse(stdout);
if (v?.Main.Version) {
cfg.version = { version: v.Main.Version, goVersion: v.GoVersion };
return cfg.version;
}
} catch (e) {
// do nothing
}
// fall back to the old way (pre v0.8.0)
let output = '';
try {
const { stdout } = await execFile(cfg.path, ['version'], { env, cwd });
output = stdout;
} catch (e) {
// The "gopls version" command is not supported, or something else went wrong.
// TODO: Should we propagate this error?
return;
}
const lines = output.trim().split('\n');
switch (lines.length) {
case 0:
// No results, should update.
// Worth doing anything here?
return;
case 1:
// Built in $GOPATH mode. Should update.
// TODO: Should we check the Go version here?
// Do we even allow users to enable gopls if their Go version is too low?
return;
case 2:
// We might actually have a parseable version.
break;
default:
return;
}
// The second line should be the sum line.
// It should look something like this:
//
// golang.org/x/tools/gopls@v0.1.3 h1:CB5ECiPysqZrwxcyRjN+exyZpY0gODTZvNiqQi3lpeo=
//
// TODO(stamblerre): We should use a regex to match this, but for now, we split on the @ symbol.
// The reasoning for this is that gopls still has a golang.org/x/tools/cmd/gopls binary,
// so users may have a developer version that looks like "golang.org/x/tools@(devel)".
const moduleVersion = lines[1].trim().split(' ')[0];
// Get the relevant portion, that is:
//
// golang.org/x/tools/gopls@v0.1.3
//
const split = moduleVersion.trim().split('@');
if (split.length < 2) {
return;
}
// The version comes after the @ symbol:
//
// v0.1.3
//
cfg.version = { version: split[1] };
return cfg.version;
};
async function goProxyRequest(tool: Tool, endpoint: string): Promise<any> {
// Get the user's value of GOPROXY.
// If it is not set, we cannot make the request.
const output = process.env['GOPROXY'];
if (!output || !output.trim()) {
return null;
}
// Try each URL set in the user's GOPROXY environment variable.
// If none is set, don't make the request.
const proxies = output.trim().split(/,|\|/);
for (const proxy of proxies) {
if (proxy === 'direct') {
continue;
}
const url = `${proxy}/${tool.importPath}/@v/${endpoint}`;
let data: string;
try {
const response = await fetch(url);
data = await response.text();
} catch (e) {
console.log(`Error sending request to ${proxy}: ${e}`);
return null;
}
return data;
}
return null;
}
// errorKind refers to the different possible kinds of gopls errors.
export enum errorKind {
initializationFailure,
crash,
manualRestart
}
// suggestGoplsIssueReport prompts users to file an issue with gopls.
export async function suggestGoplsIssueReport(
goCtx: GoExtensionContext,
cfg: LanguageServerConfig, // config used when starting this gopls.
msg: string,
reason: errorKind,
initializationError?: ResponseError<InitializeError>
) {
const issueTime = new Date();
// Don't prompt users who manually restart to file issues until gopls/v1.0.
if (reason === errorKind.manualRestart) {
return;
}
// cfg is the config used when starting this crashed gopls instance, while
// goCtx.latestConfig is the config used by the latest gopls instance.
// They may be different if gopls upgrade occurred in between.
// Let's not report issue yet if they don't match.
if (JSON.stringify(goCtx.latestConfig?.version) !== JSON.stringify(cfg.version)) {
return;
}
// The user may have an outdated version of gopls, in which case we should
// just prompt them to update, not file an issue.
const tool = getTool('gopls');
if (tool) {
const versionToUpdate = await shouldUpdateLanguageServer(tool, goCtx.latestConfig, true);
if (versionToUpdate) {
promptForUpdatingTool(tool.name, versionToUpdate, true);
return;
}
}
// Show the user the output channel content to alert them to the issue.
goCtx.serverOutputChannel?.show();
if (goCtx.latestConfig?.serverName !== 'gopls') {
return;
}
const promptForIssueOnGoplsRestartKey = 'promptForIssueOnGoplsRestart';
let saved: any;
try {
saved = JSON.parse(getFromGlobalState(promptForIssueOnGoplsRestartKey, false));
} catch (err) {
console.log(`Failed to parse as JSON ${getFromGlobalState(promptForIssueOnGoplsRestartKey, true)}: ${err}`);
return;
}
// If the user has already seen this prompt, they may have opted-out for
// the future. Only prompt again if it's been more than a year since.
if (saved) {
const dateSaved = new Date(saved['date']);
const prompt = <boolean>saved['prompt'];
if (!prompt && daysBetween(new Date(), dateSaved) <= 365) {
return;
}
}
const { sanitizedLog, failureReason } = await collectGoplsLog(goCtx);
// If the user has invalid values for "go.languageServerFlags", we may get
// this error. Prompt them to double check their flags.
let selected: string | undefined;
if (failureReason === GoplsFailureModes.INCORRECT_COMMAND_USAGE) {
const languageServerFlags = getGoConfig()['languageServerFlags'] as string[];
if (languageServerFlags && languageServerFlags.length > 0) {
selected = await vscode.window.showErrorMessage(
`The extension was unable to start the language server.
You may have an invalid value in your "go.languageServerFlags" setting.
It is currently set to [${languageServerFlags}].
Please correct the setting.`,
'Open Settings',
'I need more help.'
);
switch (selected) {
case 'Open Settings':
await vscode.commands.executeCommand('workbench.action.openSettings', 'go.languageServerFlags');
return;
case 'I need more help':
// Fall through the automated issue report.
break;
}
}
}
const showMessage = sanitizedLog ? vscode.window.showWarningMessage : vscode.window.showInformationMessage;
selected = await showMessage(
`${msg} Would you like to report a gopls issue on GitHub?
You will be asked to provide additional information and logs, so PLEASE READ THE CONTENT IN YOUR BROWSER.`,
'Yes',
'Next time',
'Never'
);
switch (selected) {
case 'Yes':
{
// Prefill an issue title and report.
let errKind: string;
switch (reason) {
case errorKind.crash:
errKind = 'crash';
break;
case errorKind.initializationFailure:
errKind = 'initialization';
break;
}
const settings = goCtx.latestConfig.flags.join(' ');
const title = `gopls: automated issue report (${errKind})`;
const goplsStats = await getGoplsStats(goCtx.latestConfig?.path);
const goplsLog = sanitizedLog
? `<pre>${sanitizedLog}</pre>`
: `Please attach the stack trace from the crash.
A window with the error message should have popped up in the lower half of your screen.
Please copy the stack trace and error messages from that window and paste it in this issue.
<PASTE STACK TRACE HERE>
Failed to auto-collect gopls trace: ${failureReason}.
`;
const body = `
gopls version: ${cfg.version?.version}/${cfg.version?.goVersion}
gopls flags: ${settings}
update flags: ${cfg.checkForUpdates}
extension version: ${extensionInfo.version}
environment: ${extensionInfo.appName} ${process.platform}
initialization error: ${initializationError}
issue timestamp: ${issueTime.toUTCString()}
restart history:
${formatRestartHistory(goCtx)}
ATTENTION: PLEASE PROVIDE THE DETAILS REQUESTED BELOW.
Describe what you observed.
<ANSWER HERE>
${goplsLog}
<details><summary>gopls stats -anon</summary>
${goplsStats}
</details>
OPTIONAL: If you would like to share more information, you can attach your complete gopls logs.
NOTE: THESE MAY CONTAIN SENSITIVE INFORMATION ABOUT YOUR CODEBASE.
DO NOT SHARE LOGS IF YOU ARE WORKING IN A PRIVATE REPOSITORY.
<OPTIONAL: ATTACH LOGS HERE>
`;
const url = `https://github.com/golang/vscode-go/issues/new?title=${title}&labels=automatedReport&body=${body}`;
await vscode.env.openExternal(vscode.Uri.parse(url));
}
break;
case 'Next time':
break;
case 'Never':
updateGlobalState(
promptForIssueOnGoplsRestartKey,
JSON.stringify({
prompt: false,
date: new Date()
})
);
break;
}
}
export const showServerOutputChannel: CommandFactory = (ctx, goCtx) => () => {
if (!goCtx.languageServerIsRunning) {
vscode.window.showInformationMessage('gopls is not running');
return;
}
// likely show() is asynchronous, despite the documentation
goCtx.serverOutputChannel?.show();
let found: vscode.TextDocument | undefined;
for (const doc of vscode.workspace.textDocuments) {
if (doc.fileName.indexOf('extension-output-') !== -1) {
// despite show() above, this might not get the output we want, so check
const contents = doc.getText();
if (contents.indexOf('[Info - ') === -1) {
continue;
}
if (found !== undefined) {
vscode.window.showInformationMessage('multiple docs named extension-output-...');
}
found = doc;
// .log, as some decoration is better than none
vscode.workspace.openTextDocument({ language: 'log', content: contents });
}
}
if (found === undefined) {
vscode.window.showErrorMessage('make sure "gopls (server)" output is showing');
}
};
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function collectGoplsLog(goCtx: GoExtensionContext): Promise<{ sanitizedLog?: string; failureReason?: string }> {
goCtx.serverOutputChannel?.show();
// Find the logs in the output channel. There is no way to read
// an output channel directly, but we can find the open text
// document, since we just surfaced the output channel to the user.
// See https://github.com/microsoft/vscode/issues/65108.
let logs: string | undefined;
for (let i = 0; i < 10; i++) {
// try a couple of times until successfully finding the channel.
for (const doc of vscode.workspace.textDocuments) {
if (doc.languageId !== 'Log') {
continue;
}
if (doc.isDirty || doc.isClosed) {
continue;
}
if (doc.fileName.indexOf('gopls (server)') > -1) {
logs = doc.getText();
break;
}
}
if (logs) {
break;
}
// sleep a bit before the next try. The choice of the sleep time is arbitrary.
await sleep((i + 1) * 100);
}
return sanitizeGoplsTrace(logs);
}
enum GoplsFailureModes {
NO_GOPLS_LOG = 'no gopls log',
EMPTY_PANIC_TRACE = 'empty panic trace',
INCORRECT_COMMAND_USAGE = 'incorrect gopls command usage',
UNRECOGNIZED_CRASH_PATTERN = 'unrecognized crash pattern'
}
// capture only panic stack trace and the initialization error message.
// exported for testing.
export function sanitizeGoplsTrace(logs?: string): { sanitizedLog?: string; failureReason?: string } {
if (!logs) {
return { failureReason: GoplsFailureModes.NO_GOPLS_LOG };
}
const panicMsgBegin = logs.lastIndexOf('panic: ');
if (panicMsgBegin > -1) {
// panic message was found.
let panicTrace = logs.substr(panicMsgBegin);
const panicMsgEnd = panicTrace.search(/\[(Info|Warning|Error)\s+-\s+/);
if (panicMsgEnd > -1) {
panicTrace = panicTrace.substr(0, panicMsgEnd);
}
const filePattern = /(\S+\.go):\d+/;
const sanitized = panicTrace
.split('\n')
.map((line: string) => {
// Even though this is a crash from gopls, the file path
// can contain user names and user's filesystem directory structure.
// We can still locate the corresponding file if the file base is
// available because the full package path is part of the function
// name. So, leave only the file base.
const m = line.match(filePattern);
if (!m) {
return line;
}
const filePath = m[1];
const fileBase = path.basename(filePath);
return line.replace(filePath, ' ' + fileBase);
})
.join('\n');
if (sanitized) {
return { sanitizedLog: sanitized };
}
return { failureReason: GoplsFailureModes.EMPTY_PANIC_TRACE };
}
// Capture Fatal
// foo.go:1: the last message (caveat - we capture only the first log line)
const m = logs.match(/(^\S+\.go:\d+:.*$)/gm);
if (m && m.length > 0) {
return { sanitizedLog: m[0].toString() };
}
const initFailMsgBegin = logs.lastIndexOf('gopls client:');
if (initFailMsgBegin > -1) {
// client start failed. Capture up to the 'Code:' line.
const initFailMsgEnd = logs.indexOf('Code: ', initFailMsgBegin);
if (initFailMsgEnd > -1) {
const lineEnd = logs.indexOf('\n', initFailMsgEnd);
return {
sanitizedLog:
lineEnd > -1
? logs.substr(initFailMsgBegin, lineEnd - initFailMsgBegin)
: logs.substr(initFailMsgBegin)
};
}
}
if (logs.lastIndexOf('Usage:') > -1) {
return { failureReason: GoplsFailureModes.INCORRECT_COMMAND_USAGE };
}
return { failureReason: GoplsFailureModes.UNRECOGNIZED_CRASH_PATTERN };
}
const GOPLS_FETCH_VULNCHECK_RESULT = 'gopls.fetch_vulncheck_result';
// Fetches vulncheck result and throws an error if the result is not found.
// uri is a string representation of URI or DocumentURI.
async function goplsFetchVulncheckResult(goCtx: GoExtensionContext, uri: string): Promise<VulncheckReport> {
const { languageClient } = goCtx;
const params: ExecuteCommandParams = {
command: GOPLS_FETCH_VULNCHECK_RESULT,
arguments: [{ URI: uri }]
};
const res: { [modFile: string]: VulncheckReport } = await languageClient?.sendRequest(
ExecuteCommandRequest.type,
params
);
// res may include multiple results, but we only need one for the given uri.
// Gopls uses normalized URI (https://cs.opensource.google/go/x/tools/+/refs/tags/gopls/v0.14.2:gopls/internal/span/uri.go;l=78)
// but VS Code URI (uri) may not be normalized. For comparison, we use URI.fsPath
// that provides a normalization implementation.
// https://github.com/microsoft/vscode-uri/blob/53e4ca6263f2e4ddc35f5360c62bc1b1d30f27dd/src/uri.ts#L204
const uriFsPath = URI.parse(uri).fsPath;
for (const modFile in res) {
try {
const modFileURI = URI.parse(modFile);
if (modFileURI.fsPath === uriFsPath) {
return res[modFile];
}
} catch (e) {
console.log(`gopls returned an unparseable file uri in govulncheck result: ${modFile}`);
}
}
throw new Error(`no matching go.mod ${uriFsPath} (${uri.toString()}) in the returned result: ${Object.keys(res)}`);
}
export function maybePromptForTelemetry(goCtx: GoExtensionContext) {
const callback = async () => {
const { lastUserAction = new Date() } = goCtx;
const currentTime = new Date();
// Make sure the user has been idle for at least 5 minutes.
const idleTime = currentTime.getTime() - lastUserAction.getTime();
if (idleTime < 5 * timeMinute) {
setTimeout(callback, 5 * timeMinute - Math.max(idleTime, 0));
return;
}
goCtx.telemetryService?.promptForTelemetry(extensionInfo.isPreview);
};
callback();
}
async function getGoplsStats(binpath?: string) {
if (!binpath) {
return 'gopls path unknown';
}
const env = toolExecutionEnvironment();
const cwd = getWorkspaceFolderPath();
const start = new Date();
const execFile = util.promisify(cp.execFile);
try {
const timeout = 60 * 1000; // 60sec;
const { stdout } = await execFile(binpath, ['stats', '-anon'], { env, cwd, timeout });
return stdout;
} catch (e) {
const duration = new Date().getTime() - start.getTime();
console.log(`gopls stats -anon failed: ${JSON.stringify(e)}`);
return `gopls stats -anon failed after ${duration} ms. Please check if gopls is killed by OS.`;
}
}
| vscode-go/extension/src/language/goLanguageServer.ts/0 | {
"file_path": "vscode-go/extension/src/language/goLanguageServer.ts",
"repo_id": "vscode-go",
"token_count": 20203
} | 786 |
/*---------------------------------------------------------
* Copyright 2022 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
// find a random day in the next 4 weeks, starting tomorrow
// (If this code is changed, run the test in calendartest.ts
// by hand.)
export function promptNext4Weeks(now: Date): Date {
const day = 24 * 3600 * 1000; // milliseconds in a day
// choose a random day in the next 4 weeks, starting tomorrow
const delta = randomIntInRange(1, 28);
const x = now.getTime() + day * delta;
return new Date(x);
}
// randomIntInRange returns a random integer between min and max, inclusive.
function randomIntInRange(min: number, max: number): number {
const low = Math.ceil(min);
const high = Math.floor(max);
return Math.floor(Math.random() * (high - low + 1)) + low;
}
| vscode-go/extension/src/utils/randomDayutils.ts/0 | {
"file_path": "vscode-go/extension/src/utils/randomDayutils.ts",
"repo_id": "vscode-go",
"token_count": 246
} | 787 |
/* eslint-disable node/no-unpublished-import */
/*---------------------------------------------------------
* Copyright 2023 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
import * as sinon from 'sinon';
import { describe, it } from 'mocha';
import {
GOPLS_MAYBE_PROMPT_FOR_TELEMETRY,
TELEMETRY_START_TIME_KEY,
TelemetryReporter,
TelemetryService,
recordTelemetryStartTime
} from '../../src/goTelemetry';
import { MockMemento } from '../mocks/MockMemento';
import { maybeInstallVSCGO } from '../../src/goInstallTools';
import assert from 'assert';
import path from 'path';
import * as fs from 'fs-extra';
import os = require('os');
import { rmdirRecursive } from '../../src/util';
import { extensionId } from '../../src/const';
import { executableFileExists, fileExists } from '../../src/utils/pathUtils';
import { ExtensionMode, Memento, extensions } from 'vscode';
describe('# prompt for telemetry', async () => {
const extension = extensions.getExtension(extensionId);
assert(extension);
it(
'do not prompt if language client is not used',
testTelemetryPrompt(
{
noLangClient: true,
previewExtension: true,
samplingInterval: 1000
},
false
)
); // no crash when there is no language client.
it(
'do not prompt if gopls does not support telemetry',
testTelemetryPrompt(
{
goplsWithoutTelemetry: true,
previewExtension: true,
samplingInterval: 1000
},
false
)
);
it(
'prompt when telemetry started a while ago',
testTelemetryPrompt(
{
firstDate: new Date('2022-01-01'),
samplingInterval: 1000
},
true
)
);
it(
'do not prompt if telemetry started two days ago',
testTelemetryPrompt(
{
firstDate: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // two days ago!
samplingInterval: 1000
},
false
)
);
it(
'do not prompt if gopls with telemetry never ran',
testTelemetryPrompt(
{
firstDate: undefined, // gopls with telemetry not seen before.
samplingInterval: 1000
},
false
)
);
it(
'do not prompt if not sampled',
testTelemetryPrompt(
{
firstDate: new Date('2022-01-01'),
samplingInterval: 0
},
false
)
);
it(
'prompt only if sampled (machineID = 0, samplingInterval = 1)',
testTelemetryPrompt(
{
firstDate: new Date('2022-01-01'),
samplingInterval: 1,
hashMachineID: 0
},
true
)
);
it(
'prompt only if sampled (machineID = 1, samplingInterval = 1)',
testTelemetryPrompt(
{
firstDate: new Date('2022-01-01'),
samplingInterval: 1,
hashMachineID: 1
},
false
)
);
it(
'prompt all preview extension users',
testTelemetryPrompt(
{
firstDate: new Date('2022-01-01'),
previewExtension: true,
samplingInterval: 0
},
true
)
);
it(
'do not prompt if vscode telemetry is disabled',
testTelemetryPrompt(
{
firstDate: new Date('2022-01-01'),
vsTelemetryDisabled: true,
previewExtension: true,
samplingInterval: 1000
},
false
)
);
// testExtensionAPI.globalState is a real memento instance passed by ExtensionHost.
// This instance is active throughout the integration test.
// When you add more test cases that interact with the globalState,
// be aware that multiple test cases may access and mutate it asynchronously.
const testExtensionAPI = await extension.activate();
it('check we can salvage the value in the real memento', async () => {
// write Date with Memento.update - old way. Now we always use string for TELEMETRY_START_TIME_KEY value.
testExtensionAPI.globalState.update(TELEMETRY_START_TIME_KEY, new Date(Date.now() - 7 * 24 * 60 * 60 * 1000));
await testTelemetryPrompt(
{
samplingInterval: 1000,
mementoInstance: testExtensionAPI.globalState
},
true
)();
});
});
interface testCase {
noLangClient?: boolean; // gopls is not running.
goplsWithoutTelemetry?: boolean; // gopls is too old.
firstDate?: Date; // first date the extension observed gopls with telemetry feature.
previewExtension?: boolean; // assume we are in dev/nightly extension.
vsTelemetryDisabled?: boolean; // assume the user disabled vscode general telemetry.
samplingInterval: number; // N where N out of 1000 are sampled.
hashMachineID?: number; // stub the machine id hash computation function.
mementoInstance?: Memento; // if set, use this instead of mock memento.
}
function testTelemetryPrompt(tc: testCase, wantPrompt: boolean) {
return async () => {
const languageClient = {
sendRequest: () => {
return Promise.resolve();
}
};
const spy = sinon.spy(languageClient, 'sendRequest');
const lc = tc.noLangClient ? undefined : languageClient;
const memento = tc.mementoInstance ?? new MockMemento();
if (tc.firstDate) {
recordTelemetryStartTime(memento, tc.firstDate);
}
const commands = tc.goplsWithoutTelemetry ? [] : [GOPLS_MAYBE_PROMPT_FOR_TELEMETRY];
const sut = new TelemetryService(lc, memento, commands);
if (tc.hashMachineID !== undefined) {
sinon.stub(sut, 'hashMachineID').returns(tc.hashMachineID);
}
await sut.promptForTelemetry(!!tc.previewExtension, !tc.vsTelemetryDisabled, tc.samplingInterval);
if (wantPrompt) {
sinon.assert.calledOnce(spy);
} else {
sinon.assert.neverCalledWith(spy);
}
};
}
describe('# telemetry reporter using vscgo', async function () {
this.timeout(10000); // go install can be slow.
// installVSCGO expects
// {extensionPath}/vscgo: vscgo source code for testing.
// {extensionPath}/bin: where compiled vscgo will be stored.
// During testing, extensionDevelopmentPath is the root of the extension.
// __dirname = out/test/gopls.
const extensionDevelopmentPath = path.resolve(__dirname, '../../..');
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'telemetryReporter'));
const counterfile = path.join(tmpDir, 'counterfile.txt');
const sut = new TelemetryReporter(0, counterfile);
let vscgo: string;
suiteSetup(async () => {
try {
vscgo = await maybeInstallVSCGO(
ExtensionMode.Test,
extensionId,
'',
extensionDevelopmentPath,
true /*isPreview*/
);
} catch (e) {
assert.fail(`failed to install vscgo needed for testing: ${e}`);
}
});
suiteTeardown(() => {
rmdirRecursive(tmpDir);
if (executableFileExists(vscgo)) {
fs.unlink(vscgo);
}
});
teardown(() => {
if (fileExists(counterfile)) {
fs.unlink(counterfile);
}
});
it('add succeeds before telemetryReporter.setTool runs', () => {
sut.add('hello', 1);
sut.add('world', 2);
});
it('flush is noop before setTool', async () => {
await sut.flush();
assert(!fileExists(counterfile), 'counterfile exists');
});
it('flush writes accumulated counters after setTool', async () => {
sut.setTool(vscgo);
await sut.flush();
const readAll = fs.readFileSync(counterfile).toString();
assert(readAll.includes('hello 1\n') && readAll.includes('world 2\n'), readAll);
});
it('dispose triggers flush', async () => {
sut.add('bye', 3);
await sut.dispose();
const readAll = fs.readFileSync(counterfile).toString();
assert(readAll.includes('bye 3\n'), readAll);
});
});
| vscode-go/extension/test/gopls/telemetry.test.ts/0 | {
"file_path": "vscode-go/extension/test/gopls/telemetry.test.ts",
"repo_id": "vscode-go",
"token_count": 2695
} | 788 |
/* eslint-disable no-prototype-builtins */
/* eslint-disable node/no-unpublished-import */
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Modification copyright 2020 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
import assert from 'assert';
import * as fs from 'fs-extra';
import { describe, it } from 'mocha';
import * as os from 'os';
import * as path from 'path';
import * as sinon from 'sinon';
import * as vscode from 'vscode';
import {
formatGoVersion,
getGoEnvironmentStatusbarItem,
getSelectedGo,
GoEnvironmentOption,
setSelectedGo
} from '../../src/goEnvironmentStatus';
import { updateGoVarsFromConfig } from '../../src/goInstallTools';
import { disposeGoStatusBar } from '../../src/goStatus';
import { getWorkspaceState, setWorkspaceState } from '../../src/stateUtils';
import { MockMemento } from '../mocks/MockMemento';
import ourutil = require('../../src/util');
import { setGOROOTEnvVar } from '../../src/goEnv';
describe('#initGoStatusBar()', function () {
this.beforeAll(async () => {
await updateGoVarsFromConfig({}); // should initialize the status bar.
});
this.afterAll(() => {
disposeGoStatusBar();
});
it('should create a status bar item', () => {
assert.notEqual(getGoEnvironmentStatusbarItem(), undefined);
});
it('should create a status bar item with a label matching go.goroot version', async () => {
const version = await ourutil.getGoVersion();
const versionLabel = formatGoVersion(version);
let label = getGoEnvironmentStatusbarItem().text;
const iconPos = label.indexOf('$');
if (iconPos >= 0) {
label = label.substring(0, iconPos);
}
assert.equal(label, versionLabel, 'goroot version does not match status bar item text');
});
});
describe('#setGOROOTEnvVar', function () {
let origGOROOT = process.env['GOROOT'];
this.beforeEach(() => {
origGOROOT = process.env['GOROOT'];
});
this.afterEach(() => {
if (origGOROOT) {
process.env['GOROOT'] = origGOROOT;
} else {
delete process.env.GOROOT;
}
delete process.env.GOROOT_FOR_TEST_SET_GOROOT_ENV_VAR;
});
it('empty goroot does not change GOROOT', async () => {
await setGOROOTEnvVar('');
assert.strictEqual(process.env['GOROOT'], origGOROOT);
});
it('{env:*} is substituted', async () => {
const goroot = path.dirname(ourutil.getBinPath('go'));
process.env['GOROOT_FOR_TEST_SET_GOROOT_ENV_VAR'] = goroot;
await setGOROOTEnvVar('${env:GOROOT_FOR_TEST_SET_GOROOT_ENV_VAR}');
assert.strictEqual(process.env['GOROOT'], process.env['GOROOT_FOR_TEST_SET_GOROOT_ENV_VAR']);
});
it('non-directory value is rejected', async () => {
await setGOROOTEnvVar(ourutil.getBinPath('go'));
assert.strictEqual(process.env['GOROOT'], origGOROOT);
});
it('directory value is accepted', async () => {
const goroot = path.join(path.dirname(ourutil.getBinPath('go')), '..');
await setGOROOTEnvVar(goroot);
assert.strictEqual(process.env['GOROOT'], goroot);
});
});
describe('#setSelectedGo()', function () {
this.timeout(40000);
let sandbox: sinon.SinonSandbox | undefined;
let goOption: GoEnvironmentOption;
let defaultMemento: vscode.Memento;
this.beforeAll(async () => {
const version = await ourutil.getGoVersion();
const defaultGoOption = new GoEnvironmentOption(version.binaryPath, formatGoVersion(version));
defaultMemento = getWorkspaceState();
setWorkspaceState(new MockMemento());
await setSelectedGo(defaultGoOption);
});
this.afterAll(async () => {
setWorkspaceState(defaultMemento);
});
this.beforeEach(async () => {
goOption = await getSelectedGo();
sandbox = sinon.createSandbox();
});
this.afterEach(async () => {
await setSelectedGo(goOption, false);
sandbox!.restore();
});
it('should update the workspace memento storage', async () => {
// set workspace setting
const workspaceTestOption = new GoEnvironmentOption('workspacetestpath', 'testlabel');
await setSelectedGo(workspaceTestOption, false);
// check that the new config is set
assert.equal(getSelectedGo()?.binpath, 'workspacetestpath');
});
it.skip('should download an uninstalled version of Go', async () => {
// TODO(https://github.com/golang/vscode-go/issues/1454): temporarily disabled
// to unblock nightly release during investigation.
if (!process.env['VSCODEGO_BEFORE_RELEASE_TESTS']) {
return;
}
// setup tmp home directory for sdk installation
const envCache = Object.assign({}, process.env);
process.env.HOME = os.tmpdir();
// set selected go as a version to download
const option = new GoEnvironmentOption('golang.org/dl/go1.13.12', 'Go 1.13.12', false);
await setSelectedGo(option, false);
// the temp sdk directory should now contain go1.13.12
const subdirs = await fs.readdir(path.join(os.tmpdir(), 'sdk'));
assert.ok(subdirs.includes('go1.13.12'), 'Go 1.13.12 was not installed');
// cleanup
process.env = envCache;
});
});
| vscode-go/extension/test/integration/statusbar.test.ts/0 | {
"file_path": "vscode-go/extension/test/integration/statusbar.test.ts",
"repo_id": "vscode-go",
"token_count": 1793
} | 789 |
package main
import (
"testing"
)
func BenchmarkSample(b *testing.B) {
b.Run("sample test passing", func(t *testing.B) {
})
b.Run("sample test failing", func(t *testing.B) {
t.FailNow()
})
testName := "dynamic test name"
b.Run(testName, func(t *testing.B) {
t.FailNow()
})
}
| vscode-go/extension/test/testdata/codelens/codelens_benchmark_test.go/0 | {
"file_path": "vscode-go/extension/test/testdata/codelens/codelens_benchmark_test.go",
"repo_id": "vscode-go",
"token_count": 122
} | 790 |
module github.com/microsoft/vscode-go/gofixtures/coveragetest
go 1.14
| vscode-go/extension/test/testdata/coverage/go.mod/0 | {
"file_path": "vscode-go/extension/test/testdata/coverage/go.mod",
"repo_id": "vscode-go",
"token_count": 28
} | 791 |
package abc
func hello() {
var x int
_ = x
} | vscode-go/extension/test/testdata/gogetdocTestData/format.go/0 | {
"file_path": "vscode-go/extension/test/testdata/gogetdocTestData/format.go",
"repo_id": "vscode-go",
"token_count": 24
} | 792 |
package main
import "time"
func main() {
for {
time.Sleep(10*time.Millisecond)
}
}
| vscode-go/extension/test/testdata/loop/loop.go/0 | {
"file_path": "vscode-go/extension/test/testdata/loop/loop.go",
"repo_id": "vscode-go",
"token_count": 37
} | 793 |
// +build randomtag
package main
import (
"fmt"
"testing"
)
// TestMe
func TestMe(t *testing.T) {
fmt.Println("Tests passed!")
}
| vscode-go/extension/test/testdata/testTags/hello_test.go/0 | {
"file_path": "vscode-go/extension/test/testdata/testTags/hello_test.go",
"repo_id": "vscode-go",
"token_count": 59
} | 794 |
jq -r .version package.json
cp ../README.md README.md
npx vsce package -o go-0.0.0-rc.1.vsix --baseContentUrl https://github.com/golang/vscode-go/raw/v0.0.0-rc.1 --baseImagesUrl https://github.com/golang/vscode-go/raw/v0.0.0-rc.1 --no-update-package-json --no-git-tag-version 0.0.0-rc.1
| vscode-go/extension/tools/release/testdata/package-v0.0.0-rc.1.golden/0 | {
"file_path": "vscode-go/extension/tools/release/testdata/package-v0.0.0-rc.1.golden",
"repo_id": "vscode-go",
"token_count": 133
} | 795 |
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package autocert
import (
"context"
"os"
"path/filepath"
"reflect"
"testing"
)
// make sure DirCache satisfies Cache interface
var _ Cache = DirCache("/")
func TestDirCache(t *testing.T) {
dir, err := os.MkdirTemp("", "autocert")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
dir = filepath.Join(dir, "certs") // a nonexistent dir
cache := DirCache(dir)
ctx := context.Background()
// test cache miss
if _, err := cache.Get(ctx, "nonexistent"); err != ErrCacheMiss {
t.Errorf("get: %v; want ErrCacheMiss", err)
}
// test put/get
b1 := []byte{1}
if err := cache.Put(ctx, "dummy", b1); err != nil {
t.Fatalf("put: %v", err)
}
b2, err := cache.Get(ctx, "dummy")
if err != nil {
t.Fatalf("get: %v", err)
}
if !reflect.DeepEqual(b1, b2) {
t.Errorf("b1 = %v; want %v", b1, b2)
}
name := filepath.Join(dir, "dummy")
if _, err := os.Stat(name); err != nil {
t.Error(err)
}
// test put deletes temp file
tmp, err := filepath.Glob(name + "?*")
if err != nil {
t.Error(err)
}
if tmp != nil {
t.Errorf("temp file exists: %s", tmp)
}
// test delete
if err := cache.Delete(ctx, "dummy"); err != nil {
t.Fatalf("delete: %v", err)
}
if _, err := cache.Get(ctx, "dummy"); err != ErrCacheMiss {
t.Errorf("get: %v; want ErrCacheMiss", err)
}
}
| crypto/acme/autocert/cache_test.go/0 | {
"file_path": "crypto/acme/autocert/cache_test.go",
"repo_id": "crypto",
"token_count": 603
} | 0 |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package argon2
import (
"bytes"
"encoding/hex"
"testing"
)
var (
genKatPassword = []byte{
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
}
genKatSalt = []byte{0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02}
genKatSecret = []byte{0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03}
genKatAAD = []byte{0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04}
)
func TestArgon2(t *testing.T) {
defer func(sse4 bool) { useSSE4 = sse4 }(useSSE4)
if useSSE4 {
t.Log("SSE4.1 version")
testArgon2i(t)
testArgon2d(t)
testArgon2id(t)
useSSE4 = false
}
t.Log("generic version")
testArgon2i(t)
testArgon2d(t)
testArgon2id(t)
}
func testArgon2d(t *testing.T) {
want := []byte{
0x51, 0x2b, 0x39, 0x1b, 0x6f, 0x11, 0x62, 0x97,
0x53, 0x71, 0xd3, 0x09, 0x19, 0x73, 0x42, 0x94,
0xf8, 0x68, 0xe3, 0xbe, 0x39, 0x84, 0xf3, 0xc1,
0xa1, 0x3a, 0x4d, 0xb9, 0xfa, 0xbe, 0x4a, 0xcb,
}
hash := deriveKey(argon2d, genKatPassword, genKatSalt, genKatSecret, genKatAAD, 3, 32, 4, 32)
if !bytes.Equal(hash, want) {
t.Errorf("derived key does not match - got: %s , want: %s", hex.EncodeToString(hash), hex.EncodeToString(want))
}
}
func testArgon2i(t *testing.T) {
want := []byte{
0xc8, 0x14, 0xd9, 0xd1, 0xdc, 0x7f, 0x37, 0xaa,
0x13, 0xf0, 0xd7, 0x7f, 0x24, 0x94, 0xbd, 0xa1,
0xc8, 0xde, 0x6b, 0x01, 0x6d, 0xd3, 0x88, 0xd2,
0x99, 0x52, 0xa4, 0xc4, 0x67, 0x2b, 0x6c, 0xe8,
}
hash := deriveKey(argon2i, genKatPassword, genKatSalt, genKatSecret, genKatAAD, 3, 32, 4, 32)
if !bytes.Equal(hash, want) {
t.Errorf("derived key does not match - got: %s , want: %s", hex.EncodeToString(hash), hex.EncodeToString(want))
}
}
func testArgon2id(t *testing.T) {
want := []byte{
0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c,
0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b, 0x53, 0xc9,
0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e,
0xb5, 0x25, 0x20, 0xe9, 0x6b, 0x01, 0xe6, 0x59,
}
hash := deriveKey(argon2id, genKatPassword, genKatSalt, genKatSecret, genKatAAD, 3, 32, 4, 32)
if !bytes.Equal(hash, want) {
t.Errorf("derived key does not match - got: %s , want: %s", hex.EncodeToString(hash), hex.EncodeToString(want))
}
}
func TestVectors(t *testing.T) {
password, salt := []byte("password"), []byte("somesalt")
for i, v := range testVectors {
want, err := hex.DecodeString(v.hash)
if err != nil {
t.Fatalf("Test %d: failed to decode hash: %v", i, err)
}
hash := deriveKey(v.mode, password, salt, nil, nil, v.time, v.memory, v.threads, uint32(len(want)))
if !bytes.Equal(hash, want) {
t.Errorf("Test %d - got: %s want: %s", i, hex.EncodeToString(hash), hex.EncodeToString(want))
}
}
}
func benchmarkArgon2(mode int, time, memory uint32, threads uint8, keyLen uint32, b *testing.B) {
password := []byte("password")
salt := []byte("choosing random salts is hard")
b.ReportAllocs()
for i := 0; i < b.N; i++ {
deriveKey(mode, password, salt, nil, nil, time, memory, threads, keyLen)
}
}
func BenchmarkArgon2i(b *testing.B) {
b.Run(" Time: 3 Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2i, 3, 32*1024, 1, 32, b) })
b.Run(" Time: 4 Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2i, 4, 32*1024, 1, 32, b) })
b.Run(" Time: 5 Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2i, 5, 32*1024, 1, 32, b) })
b.Run(" Time: 3 Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2i, 3, 64*1024, 4, 32, b) })
b.Run(" Time: 4 Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2i, 4, 64*1024, 4, 32, b) })
b.Run(" Time: 5 Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2i, 5, 64*1024, 4, 32, b) })
}
func BenchmarkArgon2d(b *testing.B) {
b.Run(" Time: 3, Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2d, 3, 32*1024, 1, 32, b) })
b.Run(" Time: 4, Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2d, 4, 32*1024, 1, 32, b) })
b.Run(" Time: 5, Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2d, 5, 32*1024, 1, 32, b) })
b.Run(" Time: 3, Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2d, 3, 64*1024, 4, 32, b) })
b.Run(" Time: 4, Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2d, 4, 64*1024, 4, 32, b) })
b.Run(" Time: 5, Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2d, 5, 64*1024, 4, 32, b) })
}
func BenchmarkArgon2id(b *testing.B) {
b.Run(" Time: 3, Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2id, 3, 32*1024, 1, 32, b) })
b.Run(" Time: 4, Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2id, 4, 32*1024, 1, 32, b) })
b.Run(" Time: 5, Memory: 32 MB, Threads: 1", func(b *testing.B) { benchmarkArgon2(argon2id, 5, 32*1024, 1, 32, b) })
b.Run(" Time: 3, Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2id, 3, 64*1024, 4, 32, b) })
b.Run(" Time: 4, Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2id, 4, 64*1024, 4, 32, b) })
b.Run(" Time: 5, Memory: 64 MB, Threads: 4", func(b *testing.B) { benchmarkArgon2(argon2id, 5, 64*1024, 4, 32, b) })
}
// Generated with the CLI of https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
var testVectors = []struct {
mode int
time, memory uint32
threads uint8
hash string
}{
{
mode: argon2i, time: 1, memory: 64, threads: 1,
hash: "b9c401d1844a67d50eae3967dc28870b22e508092e861a37",
},
{
mode: argon2d, time: 1, memory: 64, threads: 1,
hash: "8727405fd07c32c78d64f547f24150d3f2e703a89f981a19",
},
{
mode: argon2id, time: 1, memory: 64, threads: 1,
hash: "655ad15eac652dc59f7170a7332bf49b8469be1fdb9c28bb",
},
{
mode: argon2i, time: 2, memory: 64, threads: 1,
hash: "8cf3d8f76a6617afe35fac48eb0b7433a9a670ca4a07ed64",
},
{
mode: argon2d, time: 2, memory: 64, threads: 1,
hash: "3be9ec79a69b75d3752acb59a1fbb8b295a46529c48fbb75",
},
{
mode: argon2id, time: 2, memory: 64, threads: 1,
hash: "068d62b26455936aa6ebe60060b0a65870dbfa3ddf8d41f7",
},
{
mode: argon2i, time: 2, memory: 64, threads: 2,
hash: "2089f3e78a799720f80af806553128f29b132cafe40d059f",
},
{
mode: argon2d, time: 2, memory: 64, threads: 2,
hash: "68e2462c98b8bc6bb60ec68db418ae2c9ed24fc6748a40e9",
},
{
mode: argon2id, time: 2, memory: 64, threads: 2,
hash: "350ac37222f436ccb5c0972f1ebd3bf6b958bf2071841362",
},
{
mode: argon2i, time: 3, memory: 256, threads: 2,
hash: "f5bbf5d4c3836af13193053155b73ec7476a6a2eb93fd5e6",
},
{
mode: argon2d, time: 3, memory: 256, threads: 2,
hash: "f4f0669218eaf3641f39cc97efb915721102f4b128211ef2",
},
{
mode: argon2id, time: 3, memory: 256, threads: 2,
hash: "4668d30ac4187e6878eedeacf0fd83c5a0a30db2cc16ef0b",
},
{
mode: argon2i, time: 4, memory: 4096, threads: 4,
hash: "a11f7b7f3f93f02ad4bddb59ab62d121e278369288a0d0e7",
},
{
mode: argon2d, time: 4, memory: 4096, threads: 4,
hash: "935598181aa8dc2b720914aa6435ac8d3e3a4210c5b0fb2d",
},
{
mode: argon2id, time: 4, memory: 4096, threads: 4,
hash: "145db9733a9f4ee43edf33c509be96b934d505a4efb33c5a",
},
{
mode: argon2i, time: 4, memory: 1024, threads: 8,
hash: "0cdd3956aa35e6b475a7b0c63488822f774f15b43f6e6e17",
},
{
mode: argon2d, time: 4, memory: 1024, threads: 8,
hash: "83604fc2ad0589b9d055578f4d3cc55bc616df3578a896e9",
},
{
mode: argon2id, time: 4, memory: 1024, threads: 8,
hash: "8dafa8e004f8ea96bf7c0f93eecf67a6047476143d15577f",
},
{
mode: argon2i, time: 2, memory: 64, threads: 3,
hash: "5cab452fe6b8479c8661def8cd703b611a3905a6d5477fe6",
},
{
mode: argon2d, time: 2, memory: 64, threads: 3,
hash: "22474a423bda2ccd36ec9afd5119e5c8949798cadf659f51",
},
{
mode: argon2id, time: 2, memory: 64, threads: 3,
hash: "4a15b31aec7c2590b87d1f520be7d96f56658172deaa3079",
},
{
mode: argon2i, time: 3, memory: 1024, threads: 6,
hash: "d236b29c2b2a09babee842b0dec6aa1e83ccbdea8023dced",
},
{
mode: argon2d, time: 3, memory: 1024, threads: 6,
hash: "a3351b0319a53229152023d9206902f4ef59661cdca89481",
},
{
mode: argon2id, time: 3, memory: 1024, threads: 6,
hash: "1640b932f4b60e272f5d2207b9a9c626ffa1bd88d2349016",
},
}
| crypto/argon2/argon2_test.go/0 | {
"file_path": "crypto/argon2/argon2_test.go",
"repo_id": "crypto",
"token_count": 4292
} | 1 |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bn256
import (
"bytes"
"crypto/rand"
"math/big"
"testing"
)
func TestGFp2Invert(t *testing.T) {
pool := new(bnPool)
a := newGFp2(pool)
a.x.SetString("23423492374", 10)
a.y.SetString("12934872398472394827398470", 10)
inv := newGFp2(pool)
inv.Invert(a, pool)
b := newGFp2(pool).Mul(inv, a, pool)
if b.x.Int64() != 0 || b.y.Int64() != 1 {
t.Fatalf("bad result for a^-1*a: %s %s", b.x, b.y)
}
a.Put(pool)
b.Put(pool)
inv.Put(pool)
if c := pool.Count(); c > 0 {
t.Errorf("Pool count non-zero: %d\n", c)
}
}
func isZero(n *big.Int) bool {
return new(big.Int).Mod(n, p).Int64() == 0
}
func isOne(n *big.Int) bool {
return new(big.Int).Mod(n, p).Int64() == 1
}
func TestGFp6Invert(t *testing.T) {
pool := new(bnPool)
a := newGFp6(pool)
a.x.x.SetString("239487238491", 10)
a.x.y.SetString("2356249827341", 10)
a.y.x.SetString("082659782", 10)
a.y.y.SetString("182703523765", 10)
a.z.x.SetString("978236549263", 10)
a.z.y.SetString("64893242", 10)
inv := newGFp6(pool)
inv.Invert(a, pool)
b := newGFp6(pool).Mul(inv, a, pool)
if !isZero(b.x.x) ||
!isZero(b.x.y) ||
!isZero(b.y.x) ||
!isZero(b.y.y) ||
!isZero(b.z.x) ||
!isOne(b.z.y) {
t.Fatalf("bad result for a^-1*a: %s", b)
}
a.Put(pool)
b.Put(pool)
inv.Put(pool)
if c := pool.Count(); c > 0 {
t.Errorf("Pool count non-zero: %d\n", c)
}
}
func TestGFp12Invert(t *testing.T) {
pool := new(bnPool)
a := newGFp12(pool)
a.x.x.x.SetString("239846234862342323958623", 10)
a.x.x.y.SetString("2359862352529835623", 10)
a.x.y.x.SetString("928836523", 10)
a.x.y.y.SetString("9856234", 10)
a.x.z.x.SetString("235635286", 10)
a.x.z.y.SetString("5628392833", 10)
a.y.x.x.SetString("252936598265329856238956532167968", 10)
a.y.x.y.SetString("23596239865236954178968", 10)
a.y.y.x.SetString("95421692834", 10)
a.y.y.y.SetString("236548", 10)
a.y.z.x.SetString("924523", 10)
a.y.z.y.SetString("12954623", 10)
inv := newGFp12(pool)
inv.Invert(a, pool)
b := newGFp12(pool).Mul(inv, a, pool)
if !isZero(b.x.x.x) ||
!isZero(b.x.x.y) ||
!isZero(b.x.y.x) ||
!isZero(b.x.y.y) ||
!isZero(b.x.z.x) ||
!isZero(b.x.z.y) ||
!isZero(b.y.x.x) ||
!isZero(b.y.x.y) ||
!isZero(b.y.y.x) ||
!isZero(b.y.y.y) ||
!isZero(b.y.z.x) ||
!isOne(b.y.z.y) {
t.Fatalf("bad result for a^-1*a: %s", b)
}
a.Put(pool)
b.Put(pool)
inv.Put(pool)
if c := pool.Count(); c > 0 {
t.Errorf("Pool count non-zero: %d\n", c)
}
}
func TestCurveImpl(t *testing.T) {
pool := new(bnPool)
g := &curvePoint{
pool.Get().SetInt64(1),
pool.Get().SetInt64(-2),
pool.Get().SetInt64(1),
pool.Get().SetInt64(0),
}
x := pool.Get().SetInt64(32498273234)
X := newCurvePoint(pool).Mul(g, x, pool)
y := pool.Get().SetInt64(98732423523)
Y := newCurvePoint(pool).Mul(g, y, pool)
s1 := newCurvePoint(pool).Mul(X, y, pool).MakeAffine(pool)
s2 := newCurvePoint(pool).Mul(Y, x, pool).MakeAffine(pool)
if s1.x.Cmp(s2.x) != 0 ||
s2.x.Cmp(s1.x) != 0 {
t.Errorf("DH points don't match: (%s, %s) (%s, %s)", s1.x, s1.y, s2.x, s2.y)
}
pool.Put(x)
X.Put(pool)
pool.Put(y)
Y.Put(pool)
s1.Put(pool)
s2.Put(pool)
g.Put(pool)
if c := pool.Count(); c > 0 {
t.Errorf("Pool count non-zero: %d\n", c)
}
}
func TestOrderG1(t *testing.T) {
g := new(G1).ScalarBaseMult(Order)
if !g.p.IsInfinity() {
t.Error("G1 has incorrect order")
}
one := new(G1).ScalarBaseMult(new(big.Int).SetInt64(1))
g.Add(g, one)
g.p.MakeAffine(nil)
if g.p.x.Cmp(one.p.x) != 0 || g.p.y.Cmp(one.p.y) != 0 {
t.Errorf("1+0 != 1 in G1")
}
}
func TestOrderG2(t *testing.T) {
g := new(G2).ScalarBaseMult(Order)
if !g.p.IsInfinity() {
t.Error("G2 has incorrect order")
}
one := new(G2).ScalarBaseMult(new(big.Int).SetInt64(1))
g.Add(g, one)
g.p.MakeAffine(nil)
if g.p.x.x.Cmp(one.p.x.x) != 0 ||
g.p.x.y.Cmp(one.p.x.y) != 0 ||
g.p.y.x.Cmp(one.p.y.x) != 0 ||
g.p.y.y.Cmp(one.p.y.y) != 0 {
t.Errorf("1+0 != 1 in G2")
}
}
func TestOrderGT(t *testing.T) {
gt := Pair(&G1{curveGen}, &G2{twistGen})
g := new(GT).ScalarMult(gt, Order)
if !g.p.IsOne() {
t.Error("GT has incorrect order")
}
}
func TestBilinearity(t *testing.T) {
for i := 0; i < 2; i++ {
a, p1, _ := RandomG1(rand.Reader)
b, p2, _ := RandomG2(rand.Reader)
e1 := Pair(p1, p2)
e2 := Pair(&G1{curveGen}, &G2{twistGen})
e2.ScalarMult(e2, a)
e2.ScalarMult(e2, b)
minusE2 := new(GT).Neg(e2)
e1.Add(e1, minusE2)
if !e1.p.IsOne() {
t.Fatalf("bad pairing result: %s", e1)
}
}
}
func TestG1Marshal(t *testing.T) {
g := new(G1).ScalarBaseMult(new(big.Int).SetInt64(1))
form := g.Marshal()
_, ok := new(G1).Unmarshal(form)
if !ok {
t.Fatalf("failed to unmarshal")
}
g.ScalarBaseMult(Order)
form = g.Marshal()
g2, ok := new(G1).Unmarshal(form)
if !ok {
t.Fatalf("failed to unmarshal ∞")
}
if !g2.p.IsInfinity() {
t.Fatalf("∞ unmarshaled incorrectly")
}
}
func TestG2Marshal(t *testing.T) {
g := new(G2).ScalarBaseMult(new(big.Int).SetInt64(1))
form := g.Marshal()
_, ok := new(G2).Unmarshal(form)
if !ok {
t.Fatalf("failed to unmarshal")
}
g.ScalarBaseMult(Order)
form = g.Marshal()
g2, ok := new(G2).Unmarshal(form)
if !ok {
t.Fatalf("failed to unmarshal ∞")
}
if !g2.p.IsInfinity() {
t.Fatalf("∞ unmarshaled incorrectly")
}
}
func TestG1Identity(t *testing.T) {
g := new(G1).ScalarBaseMult(new(big.Int).SetInt64(0))
if !g.p.IsInfinity() {
t.Error("failure")
}
}
func TestG2Identity(t *testing.T) {
g := new(G2).ScalarBaseMult(new(big.Int).SetInt64(0))
if !g.p.IsInfinity() {
t.Error("failure")
}
}
func TestTripartiteDiffieHellman(t *testing.T) {
a, _ := rand.Int(rand.Reader, Order)
b, _ := rand.Int(rand.Reader, Order)
c, _ := rand.Int(rand.Reader, Order)
pa, _ := new(G1).Unmarshal(new(G1).ScalarBaseMult(a).Marshal())
qa, _ := new(G2).Unmarshal(new(G2).ScalarBaseMult(a).Marshal())
pb, _ := new(G1).Unmarshal(new(G1).ScalarBaseMult(b).Marshal())
qb, _ := new(G2).Unmarshal(new(G2).ScalarBaseMult(b).Marshal())
pc, _ := new(G1).Unmarshal(new(G1).ScalarBaseMult(c).Marshal())
qc, _ := new(G2).Unmarshal(new(G2).ScalarBaseMult(c).Marshal())
k1 := Pair(pb, qc)
k1.ScalarMult(k1, a)
k1Bytes := k1.Marshal()
k2 := Pair(pc, qa)
k2.ScalarMult(k2, b)
k2Bytes := k2.Marshal()
k3 := Pair(pa, qb)
k3.ScalarMult(k3, c)
k3Bytes := k3.Marshal()
if !bytes.Equal(k1Bytes, k2Bytes) || !bytes.Equal(k2Bytes, k3Bytes) {
t.Errorf("keys didn't agree")
}
}
func BenchmarkPairing(b *testing.B) {
for i := 0; i < b.N; i++ {
Pair(&G1{curveGen}, &G2{twistGen})
}
}
| crypto/bn256/bn256_test.go/0 | {
"file_path": "crypto/bn256/bn256_test.go",
"repo_id": "crypto",
"token_count": 3486
} | 2 |
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on CRYPTOGAMS code with the following comment:
// # ====================================================================
// # Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
// # project. The module is, however, dual licensed under OpenSSL and
// # CRYPTOGAMS licenses depending on where you obtain it. For further
// # details see http://www.openssl.org/~appro/cryptogams/.
// # ====================================================================
// Code for the perl script that generates the ppc64 assembler
// can be found in the cryptogams repository at the link below. It is based on
// the original from openssl.
// https://github.com/dot-asm/cryptogams/commit/a60f5b50ed908e91
// The differences in this and the original implementation are
// due to the calling conventions and initialization of constants.
//go:build gc && !purego
#include "textflag.h"
#define OUT R3
#define INP R4
#define LEN R5
#define KEY R6
#define CNT R7
#define TMP R15
#define CONSTBASE R16
#define BLOCKS R17
// for VPERMXOR
#define MASK R18
DATA consts<>+0x00(SB)/8, $0x3320646e61707865
DATA consts<>+0x08(SB)/8, $0x6b20657479622d32
DATA consts<>+0x10(SB)/8, $0x0000000000000001
DATA consts<>+0x18(SB)/8, $0x0000000000000000
DATA consts<>+0x20(SB)/8, $0x0000000000000004
DATA consts<>+0x28(SB)/8, $0x0000000000000000
DATA consts<>+0x30(SB)/8, $0x0a0b08090e0f0c0d
DATA consts<>+0x38(SB)/8, $0x0203000106070405
DATA consts<>+0x40(SB)/8, $0x090a0b080d0e0f0c
DATA consts<>+0x48(SB)/8, $0x0102030005060704
DATA consts<>+0x50(SB)/8, $0x6170786561707865
DATA consts<>+0x58(SB)/8, $0x6170786561707865
DATA consts<>+0x60(SB)/8, $0x3320646e3320646e
DATA consts<>+0x68(SB)/8, $0x3320646e3320646e
DATA consts<>+0x70(SB)/8, $0x79622d3279622d32
DATA consts<>+0x78(SB)/8, $0x79622d3279622d32
DATA consts<>+0x80(SB)/8, $0x6b2065746b206574
DATA consts<>+0x88(SB)/8, $0x6b2065746b206574
DATA consts<>+0x90(SB)/8, $0x0000000100000000
DATA consts<>+0x98(SB)/8, $0x0000000300000002
DATA consts<>+0xa0(SB)/8, $0x5566774411223300
DATA consts<>+0xa8(SB)/8, $0xddeeffcc99aabb88
DATA consts<>+0xb0(SB)/8, $0x6677445522330011
DATA consts<>+0xb8(SB)/8, $0xeeffccddaabb8899
GLOBL consts<>(SB), RODATA, $0xc0
//func chaCha20_ctr32_vsx(out, inp *byte, len int, key *[8]uint32, counter *uint32)
TEXT ·chaCha20_ctr32_vsx(SB),NOSPLIT,$64-40
MOVD out+0(FP), OUT
MOVD inp+8(FP), INP
MOVD len+16(FP), LEN
MOVD key+24(FP), KEY
MOVD counter+32(FP), CNT
// Addressing for constants
MOVD $consts<>+0x00(SB), CONSTBASE
MOVD $16, R8
MOVD $32, R9
MOVD $48, R10
MOVD $64, R11
SRD $6, LEN, BLOCKS
// for VPERMXOR
MOVD $consts<>+0xa0(SB), MASK
MOVD $16, R20
// V16
LXVW4X (CONSTBASE)(R0), VS48
ADD $80,CONSTBASE
// Load key into V17,V18
LXVW4X (KEY)(R0), VS49
LXVW4X (KEY)(R8), VS50
// Load CNT, NONCE into V19
LXVW4X (CNT)(R0), VS51
// Clear V27
VXOR V27, V27, V27
// V28
LXVW4X (CONSTBASE)(R11), VS60
// Load mask constants for VPERMXOR
LXVW4X (MASK)(R0), V20
LXVW4X (MASK)(R20), V21
// splat slot from V19 -> V26
VSPLTW $0, V19, V26
VSLDOI $4, V19, V27, V19
VSLDOI $12, V27, V19, V19
VADDUWM V26, V28, V26
MOVD $10, R14
MOVD R14, CTR
PCALIGN $16
loop_outer_vsx:
// V0, V1, V2, V3
LXVW4X (R0)(CONSTBASE), VS32
LXVW4X (R8)(CONSTBASE), VS33
LXVW4X (R9)(CONSTBASE), VS34
LXVW4X (R10)(CONSTBASE), VS35
// splat values from V17, V18 into V4-V11
VSPLTW $0, V17, V4
VSPLTW $1, V17, V5
VSPLTW $2, V17, V6
VSPLTW $3, V17, V7
VSPLTW $0, V18, V8
VSPLTW $1, V18, V9
VSPLTW $2, V18, V10
VSPLTW $3, V18, V11
// VOR
VOR V26, V26, V12
// splat values from V19 -> V13, V14, V15
VSPLTW $1, V19, V13
VSPLTW $2, V19, V14
VSPLTW $3, V19, V15
// splat const values
VSPLTISW $-16, V27
VSPLTISW $12, V28
VSPLTISW $8, V29
VSPLTISW $7, V30
PCALIGN $16
loop_vsx:
VADDUWM V0, V4, V0
VADDUWM V1, V5, V1
VADDUWM V2, V6, V2
VADDUWM V3, V7, V3
VPERMXOR V12, V0, V21, V12
VPERMXOR V13, V1, V21, V13
VPERMXOR V14, V2, V21, V14
VPERMXOR V15, V3, V21, V15
VADDUWM V8, V12, V8
VADDUWM V9, V13, V9
VADDUWM V10, V14, V10
VADDUWM V11, V15, V11
VXOR V4, V8, V4
VXOR V5, V9, V5
VXOR V6, V10, V6
VXOR V7, V11, V7
VRLW V4, V28, V4
VRLW V5, V28, V5
VRLW V6, V28, V6
VRLW V7, V28, V7
VADDUWM V0, V4, V0
VADDUWM V1, V5, V1
VADDUWM V2, V6, V2
VADDUWM V3, V7, V3
VPERMXOR V12, V0, V20, V12
VPERMXOR V13, V1, V20, V13
VPERMXOR V14, V2, V20, V14
VPERMXOR V15, V3, V20, V15
VADDUWM V8, V12, V8
VADDUWM V9, V13, V9
VADDUWM V10, V14, V10
VADDUWM V11, V15, V11
VXOR V4, V8, V4
VXOR V5, V9, V5
VXOR V6, V10, V6
VXOR V7, V11, V7
VRLW V4, V30, V4
VRLW V5, V30, V5
VRLW V6, V30, V6
VRLW V7, V30, V7
VADDUWM V0, V5, V0
VADDUWM V1, V6, V1
VADDUWM V2, V7, V2
VADDUWM V3, V4, V3
VPERMXOR V15, V0, V21, V15
VPERMXOR V12, V1, V21, V12
VPERMXOR V13, V2, V21, V13
VPERMXOR V14, V3, V21, V14
VADDUWM V10, V15, V10
VADDUWM V11, V12, V11
VADDUWM V8, V13, V8
VADDUWM V9, V14, V9
VXOR V5, V10, V5
VXOR V6, V11, V6
VXOR V7, V8, V7
VXOR V4, V9, V4
VRLW V5, V28, V5
VRLW V6, V28, V6
VRLW V7, V28, V7
VRLW V4, V28, V4
VADDUWM V0, V5, V0
VADDUWM V1, V6, V1
VADDUWM V2, V7, V2
VADDUWM V3, V4, V3
VPERMXOR V15, V0, V20, V15
VPERMXOR V12, V1, V20, V12
VPERMXOR V13, V2, V20, V13
VPERMXOR V14, V3, V20, V14
VADDUWM V10, V15, V10
VADDUWM V11, V12, V11
VADDUWM V8, V13, V8
VADDUWM V9, V14, V9
VXOR V5, V10, V5
VXOR V6, V11, V6
VXOR V7, V8, V7
VXOR V4, V9, V4
VRLW V5, V30, V5
VRLW V6, V30, V6
VRLW V7, V30, V7
VRLW V4, V30, V4
BDNZ loop_vsx
VADDUWM V12, V26, V12
VMRGEW V0, V1, V27
VMRGEW V2, V3, V28
VMRGOW V0, V1, V0
VMRGOW V2, V3, V2
VMRGEW V4, V5, V29
VMRGEW V6, V7, V30
XXPERMDI VS32, VS34, $0, VS33
XXPERMDI VS32, VS34, $3, VS35
XXPERMDI VS59, VS60, $0, VS32
XXPERMDI VS59, VS60, $3, VS34
VMRGOW V4, V5, V4
VMRGOW V6, V7, V6
VMRGEW V8, V9, V27
VMRGEW V10, V11, V28
XXPERMDI VS36, VS38, $0, VS37
XXPERMDI VS36, VS38, $3, VS39
XXPERMDI VS61, VS62, $0, VS36
XXPERMDI VS61, VS62, $3, VS38
VMRGOW V8, V9, V8
VMRGOW V10, V11, V10
VMRGEW V12, V13, V29
VMRGEW V14, V15, V30
XXPERMDI VS40, VS42, $0, VS41
XXPERMDI VS40, VS42, $3, VS43
XXPERMDI VS59, VS60, $0, VS40
XXPERMDI VS59, VS60, $3, VS42
VMRGOW V12, V13, V12
VMRGOW V14, V15, V14
VSPLTISW $4, V27
VADDUWM V26, V27, V26
XXPERMDI VS44, VS46, $0, VS45
XXPERMDI VS44, VS46, $3, VS47
XXPERMDI VS61, VS62, $0, VS44
XXPERMDI VS61, VS62, $3, VS46
VADDUWM V0, V16, V0
VADDUWM V4, V17, V4
VADDUWM V8, V18, V8
VADDUWM V12, V19, V12
CMPU LEN, $64
BLT tail_vsx
// Bottom of loop
LXVW4X (INP)(R0), VS59
LXVW4X (INP)(R8), VS60
LXVW4X (INP)(R9), VS61
LXVW4X (INP)(R10), VS62
VXOR V27, V0, V27
VXOR V28, V4, V28
VXOR V29, V8, V29
VXOR V30, V12, V30
STXVW4X VS59, (OUT)(R0)
STXVW4X VS60, (OUT)(R8)
ADD $64, INP
STXVW4X VS61, (OUT)(R9)
ADD $-64, LEN
STXVW4X VS62, (OUT)(R10)
ADD $64, OUT
BEQ done_vsx
VADDUWM V1, V16, V0
VADDUWM V5, V17, V4
VADDUWM V9, V18, V8
VADDUWM V13, V19, V12
CMPU LEN, $64
BLT tail_vsx
LXVW4X (INP)(R0), VS59
LXVW4X (INP)(R8), VS60
LXVW4X (INP)(R9), VS61
LXVW4X (INP)(R10), VS62
VXOR V27, V0, V27
VXOR V28, V4, V28
VXOR V29, V8, V29
VXOR V30, V12, V30
STXVW4X VS59, (OUT)(R0)
STXVW4X VS60, (OUT)(R8)
ADD $64, INP
STXVW4X VS61, (OUT)(R9)
ADD $-64, LEN
STXVW4X VS62, (OUT)(V10)
ADD $64, OUT
BEQ done_vsx
VADDUWM V2, V16, V0
VADDUWM V6, V17, V4
VADDUWM V10, V18, V8
VADDUWM V14, V19, V12
CMPU LEN, $64
BLT tail_vsx
LXVW4X (INP)(R0), VS59
LXVW4X (INP)(R8), VS60
LXVW4X (INP)(R9), VS61
LXVW4X (INP)(R10), VS62
VXOR V27, V0, V27
VXOR V28, V4, V28
VXOR V29, V8, V29
VXOR V30, V12, V30
STXVW4X VS59, (OUT)(R0)
STXVW4X VS60, (OUT)(R8)
ADD $64, INP
STXVW4X VS61, (OUT)(R9)
ADD $-64, LEN
STXVW4X VS62, (OUT)(R10)
ADD $64, OUT
BEQ done_vsx
VADDUWM V3, V16, V0
VADDUWM V7, V17, V4
VADDUWM V11, V18, V8
VADDUWM V15, V19, V12
CMPU LEN, $64
BLT tail_vsx
LXVW4X (INP)(R0), VS59
LXVW4X (INP)(R8), VS60
LXVW4X (INP)(R9), VS61
LXVW4X (INP)(R10), VS62
VXOR V27, V0, V27
VXOR V28, V4, V28
VXOR V29, V8, V29
VXOR V30, V12, V30
STXVW4X VS59, (OUT)(R0)
STXVW4X VS60, (OUT)(R8)
ADD $64, INP
STXVW4X VS61, (OUT)(R9)
ADD $-64, LEN
STXVW4X VS62, (OUT)(R10)
ADD $64, OUT
MOVD $10, R14
MOVD R14, CTR
BNE loop_outer_vsx
done_vsx:
// Increment counter by number of 64 byte blocks
MOVD (CNT), R14
ADD BLOCKS, R14
MOVD R14, (CNT)
RET
tail_vsx:
ADD $32, R1, R11
MOVD LEN, CTR
// Save values on stack to copy from
STXVW4X VS32, (R11)(R0)
STXVW4X VS36, (R11)(R8)
STXVW4X VS40, (R11)(R9)
STXVW4X VS44, (R11)(R10)
ADD $-1, R11, R12
ADD $-1, INP
ADD $-1, OUT
PCALIGN $16
looptail_vsx:
// Copying the result to OUT
// in bytes.
MOVBZU 1(R12), KEY
MOVBZU 1(INP), TMP
XOR KEY, TMP, KEY
MOVBU KEY, 1(OUT)
BDNZ looptail_vsx
// Clear the stack values
STXVW4X VS48, (R11)(R0)
STXVW4X VS48, (R11)(R8)
STXVW4X VS48, (R11)(R9)
STXVW4X VS48, (R11)(R10)
BR done_vsx
| crypto/chacha20/chacha_ppc64le.s/0 | {
"file_path": "crypto/chacha20/chacha_ppc64le.s",
"repo_id": "crypto",
"token_count": 5154
} | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.