text
stringlengths
2
1.1M
id
stringlengths
11
117
metadata
dict
__index_level_0__
int64
0
885
// 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. // This file opens a back door to the parser for golang.org/x/tools/go/gccgoexportdata. package gccgoimporter import ( "go/types" "io" ) // Parse reads and parses gccgo export data from in and constructs a // Package, inserting it into the imports map. func Parse(in io.Reader, imports map[string]*types.Package, path string) (_ *types.Package, err error) { var p parser p.init(path, in, imports) defer func() { switch x := recover().(type) { case nil: // success case importError: err = x default: panic(x) // resume unexpected panic } }() pkg := p.parsePackage() imports[path] = pkg return pkg, err }
tools/go/internal/gccgoimporter/backdoor.go/0
{ "file_path": "tools/go/internal/gccgoimporter/backdoor.go", "repo_id": "tools", "token_count": 272 }
704
v2; package escapeinfo; prefix go; package escapeinfo go.escapeinfo go.escapeinfo; func NewT (data <type 1 [] <type -20>>) <type 2 *<type 3 "T" <type 4 struct { .go.escapeinfo.data <type 5 [] <type -20>>; }> func (? <type 6 *<type 3>>) Read (p <esc:0x1> <type 7 [] <type -20>>); >>; type <type 3>; checksum 3500838130783C0059CD0C81527F60E9738E3ACE;
tools/go/internal/gccgoimporter/testdata/escapeinfo.gox/0
{ "file_path": "tools/go/internal/gccgoimporter/testdata/escapeinfo.gox", "repo_id": "tools", "token_count": 144 }
705
package notinheap //go:notinheap type S struct{}
tools/go/internal/gccgoimporter/testdata/notinheap.go/0
{ "file_path": "tools/go/internal/gccgoimporter/testdata/notinheap.go", "repo_id": "tools", "token_count": 21 }
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 ( "os" "path/filepath" "reflect" "sort" "testing" "golang.org/x/tools/go/packages/packagestest" ) var testdata = []packagestest.Module{{ Name: "golang.org/fake1", Files: map[string]interface{}{ "a.go": packagestest.Symlink("testdata/a.go"), // broken symlink "b.go": "invalid file contents", }, Overlay: map[string][]byte{ "b.go": []byte("package fake1"), "c.go": []byte("package fake1"), }, }, { Name: "golang.org/fake2", Files: map[string]interface{}{ "other/a.go": "package fake2", }, }, { Name: "golang.org/fake2/v2", Files: map[string]interface{}{ "other/a.go": "package fake2", }, }, { Name: "golang.org/fake3@v1.0.0", Files: map[string]interface{}{ "other/a.go": "package fake3", }, }, { Name: "golang.org/fake3@v1.1.0", Files: map[string]interface{}{ "other/a.go": "package fake3", }, }} type fileTest struct { module, fragment, expect string check func(t *testing.T, exported *packagestest.Exported, filename string) } func checkFiles(t *testing.T, exported *packagestest.Exported, tests []fileTest) { for _, test := range tests { expect := filepath.Join(exported.Temp(), filepath.FromSlash(test.expect)) got := exported.File(test.module, test.fragment) if got == "" { t.Errorf("File %v missing from the output", expect) } else if got != expect { t.Errorf("Got file %v, expected %v", got, expect) } if test.check != nil { test.check(t, exported, got) } } } func checkLink(expect string) func(t *testing.T, exported *packagestest.Exported, filename string) { expect = filepath.FromSlash(expect) return func(t *testing.T, exported *packagestest.Exported, filename string) { if target, err := os.Readlink(filename); err != nil { t.Errorf("Error checking link %v: %v", filename, err) } else if target != expect { t.Errorf("Link %v does not match, got %v expected %v", filename, target, expect) } } } func checkContent(expect string) func(t *testing.T, exported *packagestest.Exported, filename string) { return func(t *testing.T, exported *packagestest.Exported, filename string) { if content, err := exported.FileContents(filename); err != nil { t.Errorf("Error reading %v: %v", filename, err) } else if string(content) != expect { t.Errorf("Content of %v does not match, got %v expected %v", filename, string(content), expect) } } } func TestGroupFilesByModules(t *testing.T) { for _, tt := range []struct { testdir string want []packagestest.Module }{ { testdir: "testdata/groups/one", want: []packagestest.Module{ { Name: "testdata/groups/one", Files: map[string]interface{}{ "main.go": true, }, }, { Name: "example.com/extra", Files: map[string]interface{}{ "help.go": true, }, }, }, }, { testdir: "testdata/groups/two", want: []packagestest.Module{ { Name: "testdata/groups/two", Files: map[string]interface{}{ "main.go": true, "expect/yo.go": true, "expect/yo_test.go": true, }, }, { Name: "example.com/extra", Files: map[string]interface{}{ "yo.go": true, "geez/help.go": true, }, }, { Name: "example.com/extra/v2", Files: map[string]interface{}{ "me.go": true, "geez/help.go": true, }, }, { Name: "example.com/tempmod", Files: map[string]interface{}{ "main.go": true, }, }, { Name: "example.com/what@v1.0.0", Files: map[string]interface{}{ "main.go": true, }, }, { Name: "example.com/what@v1.1.0", Files: map[string]interface{}{ "main.go": true, }, }, }, }, } { t.Run(tt.testdir, func(t *testing.T) { got, err := packagestest.GroupFilesByModules(tt.testdir) if err != nil { t.Fatalf("could not group files %v", err) } if len(got) != len(tt.want) { t.Fatalf("%s: wanted %d modules but got %d", tt.testdir, len(tt.want), len(got)) } for i, w := range tt.want { g := got[i] if filepath.FromSlash(g.Name) != filepath.FromSlash(w.Name) { t.Fatalf("%s: wanted module[%d].Name to be %s but got %s", tt.testdir, i, filepath.FromSlash(w.Name), filepath.FromSlash(g.Name)) } for fh := range w.Files { if _, ok := g.Files[fh]; !ok { t.Fatalf("%s, module[%d]: wanted %s but could not find", tt.testdir, i, fh) } } for fh := range g.Files { if _, ok := w.Files[fh]; !ok { t.Fatalf("%s, module[%d]: found unexpected file %s", tt.testdir, i, fh) } } } }) } } func TestMustCopyFiles(t *testing.T) { // Create the following test directory structure in a temporary directory. src := map[string]string{ // copies all files under the specified directory. "go.mod": "module example.com", "m.go": "package m", "a/a.go": "package a", // contents from a nested module shouldn't be copied. "nested/go.mod": "module example.com/nested", "nested/m.go": "package nested", "nested/b/b.go": "package b", } tmpDir, err := os.MkdirTemp("", t.Name()) if err != nil { t.Fatalf("failed to create a temporary directory: %v", err) } defer os.RemoveAll(tmpDir) for fragment, contents := range src { fullpath := filepath.Join(tmpDir, filepath.FromSlash(fragment)) if err := os.MkdirAll(filepath.Dir(fullpath), 0755); err != nil { t.Fatal(err) } if err := os.WriteFile(fullpath, []byte(contents), 0644); err != nil { t.Fatal(err) } } copied := packagestest.MustCopyFileTree(tmpDir) var got []string for fragment := range copied { got = append(got, filepath.ToSlash(fragment)) } want := []string{"go.mod", "m.go", "a/a.go"} sort.Strings(got) sort.Strings(want) if !reflect.DeepEqual(got, want) { t.Errorf("packagestest.MustCopyFileTree = %v, want %v", got, want) } // packagestest.Export is happy. exported := packagestest.Export(t, packagestest.Modules, []packagestest.Module{{ Name: "example.com", Files: packagestest.MustCopyFileTree(tmpDir), }}) defer exported.Cleanup() }
tools/go/packages/packagestest/export_test.go/0
{ "file_path": "tools/go/packages/packagestest/export_test.go", "repo_id": "tools", "token_count": 2778 }
707
package two
tools/go/packages/packagestest/testdata/groups/two/primarymod/main.go/0
{ "file_path": "tools/go/packages/packagestest/testdata/groups/two/primarymod/main.go", "repo_id": "tools", "token_count": 2 }
708
// 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 ssa import ( "go/types" "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/typeparams" ) // Utilities for dealing with core types. // isBytestring returns true if T has the same terms as interface{[]byte | string}. // These act like a core type for some operations: slice expressions, append and copy. // // See https://go.dev/ref/spec#Core_types for the details on bytestring. func isBytestring(T types.Type) bool { U := T.Underlying() if _, ok := U.(*types.Interface); !ok { return false } tset := typeSetOf(U) if tset.Len() != 2 { return false } hasBytes, hasString := false, false underIs(tset, func(t types.Type) bool { switch { case isString(t): hasString = true case isByteSlice(t): hasBytes = true } return hasBytes || hasString }) return hasBytes && hasString } // termList is a list of types. type termList []*types.Term // type terms of the type set func (s termList) Len() int { return len(s) } func (s termList) At(i int) types.Type { return s[i].Type() } // typeSetOf returns the type set of typ. Returns an empty typeset on an error. func typeSetOf(typ types.Type) termList { // This is a adaptation of x/exp/typeparams.NormalTerms which x/tools cannot depend on. var terms []*types.Term var err error // typeSetOf(t) == typeSetOf(Unalias(t)) switch typ := aliases.Unalias(typ).(type) { case *types.TypeParam: terms, err = typeparams.StructuralTerms(typ) case *types.Union: terms, err = typeparams.UnionTermSet(typ) case *types.Interface: terms, err = typeparams.InterfaceTermSet(typ) default: // Common case. // Specializing the len=1 case to avoid a slice // had no measurable space/time benefit. terms = []*types.Term{types.NewTerm(false, typ)} } if err != nil { return termList(nil) } return termList(terms) } // underIs calls f with the underlying types of the specific type terms // of s and reports whether all calls to f returned true. If there are // no specific terms, underIs returns the result of f(nil). func underIs(s termList, f func(types.Type) bool) bool { if s.Len() == 0 { return f(nil) } for i := 0; i < s.Len(); i++ { u := s.At(i).Underlying() if !f(u) { return false } } return true } // indexType returns the element type and index mode of a IndexExpr over a type. // It returns (nil, invalid) if the type is not indexable; this should never occur in a well-typed program. func indexType(typ types.Type) (types.Type, indexMode) { switch U := typ.Underlying().(type) { case *types.Array: return U.Elem(), ixArrVar case *types.Pointer: if arr, ok := U.Elem().Underlying().(*types.Array); ok { return arr.Elem(), ixVar } case *types.Slice: return U.Elem(), ixVar case *types.Map: return U.Elem(), ixMap case *types.Basic: return tByte, ixValue // must be a string case *types.Interface: tset := typeSetOf(U) if tset.Len() == 0 { return nil, ixInvalid // no underlying terms or error is empty. } elem, mode := indexType(tset.At(0)) for i := 1; i < tset.Len() && mode != ixInvalid; i++ { e, m := indexType(tset.At(i)) if !types.Identical(elem, e) { // if type checked, just a sanity check return nil, ixInvalid } // Update the mode to the most constrained address type. mode = mode.meet(m) } if mode != ixInvalid { return elem, mode } } return nil, ixInvalid } // An indexMode specifies the (addressing) mode of an index operand. // // Addressing mode of an index operation is based on the set of // underlying types. // Hasse diagram of the indexMode meet semi-lattice: // // ixVar ixMap // | | // ixArrVar | // | | // ixValue | // \ / // ixInvalid type indexMode byte const ( ixInvalid indexMode = iota // index is invalid ixValue // index is a computed value (not addressable) ixArrVar // like ixVar, but index operand contains an array ixVar // index is an addressable variable ixMap // index is a map index expression (acts like a variable on lhs, commaok on rhs of an assignment) ) // meet is the address type that is constrained by both x and y. func (x indexMode) meet(y indexMode) indexMode { if (x == ixMap || y == ixMap) && x != y { return ixInvalid } // Use int representation and return min. if x < y { return y } return x }
tools/go/ssa/coretype.go/0
{ "file_path": "tools/go/ssa/coretype.go", "repo_id": "tools", "token_count": 1719 }
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_test // This test runs the SSA interpreter over sample Go programs. // Because the interpreter requires intrinsics for assembly // functions and many low-level runtime routines, it is inherently // not robust to evolutionary change in the standard library. // Therefore the test cases are restricted to programs that // use a fake standard library in testdata/src containing a tiny // subset of simple functions useful for writing assertions. // // We no longer attempt to interpret any real standard packages such as // fmt or testing, as it proved too fragile. import ( "bytes" "fmt" "go/build" "go/types" "log" "os" "path/filepath" "runtime" "strings" "testing" "time" "unsafe" "golang.org/x/tools/go/loader" "golang.org/x/tools/go/ssa" "golang.org/x/tools/go/ssa/interp" "golang.org/x/tools/go/ssa/ssautil" "golang.org/x/tools/internal/testenv" ) // Each line contains a space-separated list of $GOROOT/test/ // filenames comprising the main package of a program. // They are ordered quickest-first, roughly. // // If a test in this list fails spuriously, remove it. var gorootTestTests = []string{ "235.go", "alias1.go", "func5.go", "func6.go", "func7.go", "func8.go", "helloworld.go", "varinit.go", "escape3.go", "initcomma.go", "cmp.go", "compos.go", "turing.go", "indirect.go", "complit.go", "for.go", "struct0.go", "intcvt.go", "printbig.go", "deferprint.go", "escape.go", "range.go", "const4.go", "float_lit.go", "bigalg.go", "decl.go", "if.go", "named.go", "bigmap.go", "func.go", "reorder2.go", "gc.go", "simassign.go", "iota.go", "nilptr2.go", "utf.go", "method.go", "char_lit.go", "env.go", "int_lit.go", "string_lit.go", "defer.go", "typeswitch.go", "stringrange.go", "reorder.go", "method3.go", "literal.go", "nul1.go", // doesn't actually assert anything (errorcheckoutput) "zerodivide.go", "convert.go", "convT2X.go", "switch.go", "ddd.go", "blank.go", // partly disabled "closedchan.go", "divide.go", "rename.go", "nil.go", "recover1.go", "recover2.go", "recover3.go", "typeswitch1.go", "floatcmp.go", "crlf.go", // doesn't actually assert anything (runoutput) } // These are files in go.tools/go/ssa/interp/testdata/. var testdataTests = []string{ "boundmeth.go", "complit.go", "convert.go", "coverage.go", "deepequal.go", "defer.go", "fieldprom.go", "forvarlifetime_old.go", "ifaceconv.go", "ifaceprom.go", "initorder.go", "methprom.go", "mrvchain.go", "range.go", "recover.go", "reflect.go", "slice2arrayptr.go", "static.go", "width32.go", "rangevarlifetime_old.go", "fixedbugs/issue52342.go", "fixedbugs/issue55115.go", "fixedbugs/issue52835.go", "fixedbugs/issue55086.go", "fixedbugs/issue66783.go", "typeassert.go", "zeros.go", } func init() { // GOROOT/test used to assume that GOOS and GOARCH were explicitly set in the // environment, so do that here for TestGorootTest. os.Setenv("GOOS", runtime.GOOS) os.Setenv("GOARCH", runtime.GOARCH) } func run(t *testing.T, input string, goroot string) { // The recover2 test case is broken on Go 1.14+. See golang/go#34089. // TODO(matloob): Fix this. if filepath.Base(input) == "recover2.go" { t.Skip("The recover2.go test is broken in go1.14+. See golang.org/issue/34089.") } t.Logf("Input: %s\n", input) start := time.Now() ctx := build.Default // copy ctx.GOROOT = goroot ctx.GOOS = runtime.GOOS ctx.GOARCH = runtime.GOARCH if filepath.Base(input) == "width32.go" && unsafe.Sizeof(int(0)) > 4 { t.Skipf("skipping: width32.go checks behavior for a 32-bit int") } gover := "" if p := testenv.Go1Point(); p > 0 { gover = fmt.Sprintf("go1.%d", p) } conf := loader.Config{Build: &ctx, TypeChecker: types.Config{GoVersion: gover}} if _, err := conf.FromArgs([]string{input}, true); err != nil { t.Fatalf("FromArgs(%s) failed: %s", input, err) } conf.Import("runtime") // Print a helpful hint if we don't make it to the end. var hint string defer func() { if hint != "" { fmt.Println("FAIL") fmt.Println(hint) } else { fmt.Println("PASS") } interp.CapturedOutput = nil }() hint = fmt.Sprintf("To dump SSA representation, run:\n%% go build golang.org/x/tools/cmd/ssadump && ./ssadump -test -build=CFP %s\n", input) iprog, err := conf.Load() if err != nil { t.Fatalf("conf.Load(%s) failed: %s", input, err) } bmode := ssa.InstantiateGenerics | ssa.SanityCheckFunctions // bmode |= ssa.PrintFunctions // enable for debugging prog := ssautil.CreateProgram(iprog, bmode) prog.Build() mainPkg := prog.Package(iprog.Created[0].Pkg) if mainPkg == nil { t.Fatalf("not a main package: %s", input) } interp.CapturedOutput = new(bytes.Buffer) sizes := types.SizesFor("gc", ctx.GOARCH) if sizes.Sizeof(types.Typ[types.Int]) < 4 { panic("bogus SizesFor") } hint = fmt.Sprintf("To trace execution, run:\n%% go build golang.org/x/tools/cmd/ssadump && ./ssadump -build=C -test -run --interp=T %s\n", input) var imode interp.Mode // default mode // imode |= interp.DisableRecover // enable for debugging // imode |= interp.EnableTracing // enable for debugging exitCode := interp.Interpret(mainPkg, imode, sizes, input, []string{}) if exitCode != 0 { t.Fatalf("interpreting %s: exit code was %d", input, exitCode) } // $GOROOT/test tests use this convention: if strings.Contains(interp.CapturedOutput.String(), "BUG") { t.Fatalf("interpreting %s: exited zero but output contained 'BUG'", input) } hint = "" // call off the hounds if false { t.Log(input, time.Since(start)) // test profiling } } // makeGoroot copies testdata/src into the "src" directory of a temporary // location to mimic GOROOT/src, and adds a file "runtime/consts.go" containing // declarations for GOOS and GOARCH that match the GOOS and GOARCH of this test. // // It returns the directory that should be used for GOROOT. func makeGoroot(t *testing.T) string { goroot := t.TempDir() src := filepath.Join(goroot, "src") err := filepath.Walk("testdata/src", func(path string, info os.FileInfo, err error) error { if err != nil { return err } rel, err := filepath.Rel("testdata/src", path) if err != nil { return err } targ := filepath.Join(src, rel) if info.IsDir() { return os.Mkdir(targ, info.Mode().Perm()|0700) } b, err := os.ReadFile(path) if err != nil { return err } return os.WriteFile(targ, b, info.Mode().Perm()) }) if err != nil { t.Fatal(err) } constsGo := fmt.Sprintf(`package runtime const GOOS = %q const GOARCH = %q `, runtime.GOOS, runtime.GOARCH) err = os.WriteFile(filepath.Join(src, "runtime/consts.go"), []byte(constsGo), 0644) if err != nil { t.Fatal(err) } return goroot } // TestTestdataFiles runs the interpreter on testdata/*.go. func TestTestdataFiles(t *testing.T) { goroot := makeGoroot(t) cwd, err := os.Getwd() if err != nil { log.Fatal(err) } for _, input := range testdataTests { t.Run(input, func(t *testing.T) { run(t, filepath.Join(cwd, "testdata", input), goroot) }) } } // TestGorootTest runs the interpreter on $GOROOT/test/*.go. func TestGorootTest(t *testing.T) { goroot := makeGoroot(t) for _, input := range gorootTestTests { t.Run(input, func(t *testing.T) { run(t, filepath.Join(build.Default.GOROOT, "test", input), goroot) }) } } // TestTypeparamTest runs the interpreter on runnable examples // in $GOROOT/test/typeparam/*.go. func TestTypeparamTest(t *testing.T) { goroot := makeGoroot(t) // Skip known failures for the given reason. // TODO(taking): Address these. skip := map[string]string{ "chans.go": "interp tests do not support runtime.SetFinalizer", "issue23536.go": "unknown reason", "issue48042.go": "interp tests do not handle reflect.Value.SetInt", "issue47716.go": "interp tests do not handle unsafe.Sizeof", "issue50419.go": "interp tests do not handle dispatch to String() correctly", "issue51733.go": "interp does not handle unsafe casts", "ordered.go": "math.NaN() comparisons not being handled correctly", "orderedmap.go": "interp tests do not support runtime.SetFinalizer", "stringer.go": "unknown reason", "issue48317.go": "interp tests do not support encoding/json", "issue48318.go": "interp tests do not support encoding/json", "issue58513.go": "interp tests do not support runtime.Caller", } // Collect all of the .go files in dir that are runnable. dir := filepath.Join(build.Default.GOROOT, "test", "typeparam") list, err := os.ReadDir(dir) if err != nil { t.Fatal(err) } for _, entry := range list { if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") { continue // Consider standalone go files. } t.Run(entry.Name(), func(t *testing.T) { input := filepath.Join(dir, entry.Name()) src, err := os.ReadFile(input) if err != nil { t.Fatal(err) } // Only build test files that can be compiled, or compiled and run. if !bytes.HasPrefix(src, []byte("// run")) || bytes.HasPrefix(src, []byte("// rundir")) { t.Logf("Not a `// run` file: %s", entry.Name()) return } if reason := skip[entry.Name()]; reason != "" { t.Skipf("skipping: %s", reason) } run(t, input, goroot) }) } }
tools/go/ssa/interp/interp_test.go/0
{ "file_path": "tools/go/ssa/interp/interp_test.go", "repo_id": "tools", "token_count": 3737 }
710
// 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. //go:build go1.22 package main import ( "reflect" ) func main() { test_init() bound() manyvars() nocond() nopost() address_sequences() post_escapes() // Clones from cmd/compile/internal/loopvar/testdata . for_complicated_esc_address() for_esc_address() for_esc_closure() for_esc_method() } // After go1.22, each i will have a distinct address and value. var distinct = func(m, n int) []*int { var r []*int for i := m; i <= n; i++ { r = append(r, &i) } return r }(3, 5) func test_init() { if len(distinct) != 3 { panic(distinct) } for i, v := range []int{3, 4, 5} { if v != *(distinct[i]) { panic(distinct) } } } func bound() { b := func(k int) func() int { var f func() int for i := 0; i < k; i++ { f = func() int { return i } // address before post updates i. So last value in the body. } return f } if got := b(0); got != nil { panic(got) } if got := b(5); got() != 4 { panic(got()) } } func manyvars() { // Tests declaring many variables and having one in the middle escape. var f func() int for i, j, k, l, m, n, o, p := 7, 6, 5, 4, 3, 2, 1, 0; p < 6; l, p = l+1, p+1 { _, _, _, _, _, _, _, _ = i, j, k, l, m, n, o, p f = func() int { return l } // address *before* post updates l } if f() != 9 { // l == p+4 panic(f()) } } func nocond() { var c, b, e *int for p := 0; ; p++ { if p%7 == 0 { c = &p continue } else if p == 20 { b = &p break } e = &p } if *c != 14 { panic(c) } if *b != 20 { panic(b) } if *e != 19 { panic(e) } } func nopost() { var first, last *int for p := 0; p < 20; { if first == nil { first = &p } last = &p p++ } if *first != 1 { panic(first) } if *last != 20 { panic(last) } } func address_sequences() { var c, b, p []*int cond := func(x *int) bool { c = append(c, x) return *x < 5 } body := func(x *int) { b = append(b, x) } post := func(x *int) { p = append(p, x) (*x)++ } for i := 0; cond(&i); post(&i) { body(&i) } if c[0] == c[1] { panic(c) } if !reflect.DeepEqual(c[:5], b) { panic(c) } if !reflect.DeepEqual(c[1:], p) { panic(c) } if !reflect.DeepEqual(b[1:], p[:4]) { panic(b) } } func post_escapes() { var p []*int post := func(x *int) { p = append(p, x) (*x)++ } for i := 0; i < 5; post(&i) { } var got []int for _, x := range p { got = append(got, *x) } if want := []int{1, 2, 3, 4, 5}; !reflect.DeepEqual(got, want) { panic(got) } } func for_complicated_esc_address() { // Clone of for_complicated_esc_adress.go ss, sa := shared(23) ps, pa := private(23) es, ea := experiment(23) if ss != ps || ss != es || ea != pa || sa == pa { println("shared s, a", ss, sa, "; private, s, a", ps, pa, "; experiment s, a", es, ea) panic("for_complicated_esc_address") } } func experiment(x int) (int, int) { sum := 0 var is []*int for i := x; i != 1; i = i / 2 { for j := 0; j < 10; j++ { if i == j { // 10 skips continue } sum++ } i = i*3 + 1 if i&1 == 0 { is = append(is, &i) for i&2 == 0 { i = i >> 1 } } else { i = i + i } } asum := 0 for _, pi := range is { asum += *pi } return sum, asum } func private(x int) (int, int) { sum := 0 var is []*int I := x for ; I != 1; I = I / 2 { i := I for j := 0; j < 10; j++ { if i == j { // 10 skips I = i continue } sum++ } i = i*3 + 1 if i&1 == 0 { is = append(is, &i) for i&2 == 0 { i = i >> 1 } } else { i = i + i } I = i } asum := 0 for _, pi := range is { asum += *pi } return sum, asum } func shared(x int) (int, int) { sum := 0 var is []*int i := x for ; i != 1; i = i / 2 { for j := 0; j < 10; j++ { if i == j { // 10 skips continue } sum++ } i = i*3 + 1 if i&1 == 0 { is = append(is, &i) for i&2 == 0 { i = i >> 1 } } else { i = i + i } } asum := 0 for _, pi := range is { asum += *pi } return sum, asum } func for_esc_address() { // Clone of for_esc_address.go sum := 0 var is []*int for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if i == j { // 10 skips continue } sum++ } if i&1 == 0 { is = append(is, &i) } } bug := false if sum != 100-10 { println("wrong sum, expected", 90, ", saw", sum) bug = true } if len(is) != 5 { println("wrong iterations, expected ", 5, ", saw", len(is)) bug = true } sum = 0 for _, pi := range is { sum += *pi } if sum != 0+2+4+6+8 { println("wrong sum, expected ", 20, ", saw ", sum) bug = true } if bug { panic("for_esc_address") } } func for_esc_closure() { var is []func() int // Clone of for_esc_closure.go sum := 0 for i := 0; i < 10; i++ { for j := 0; j < 10; j++ { if i == j { // 10 skips continue } sum++ } if i&1 == 0 { is = append(is, func() int { if i%17 == 15 { i++ } return i }) } } bug := false if sum != 100-10 { println("wrong sum, expected ", 90, ", saw", sum) bug = true } if len(is) != 5 { println("wrong iterations, expected ", 5, ", saw", len(is)) bug = true } sum = 0 for _, f := range is { sum += f() } if sum != 0+2+4+6+8 { println("wrong sum, expected ", 20, ", saw ", sum) bug = true } if bug { panic("for_esc_closure") } } type I int func (x *I) method() int { return int(*x) } func for_esc_method() { // Clone of for_esc_method.go var is []func() int sum := 0 for i := I(0); int(i) < 10; i++ { for j := 0; j < 10; j++ { if int(i) == j { // 10 skips continue } sum++ } if i&1 == 0 { is = append(is, i.method) } } bug := false if sum != 100-10 { println("wrong sum, expected ", 90, ", saw ", sum) bug = true } if len(is) != 5 { println("wrong iterations, expected ", 5, ", saw", len(is)) bug = true } sum = 0 for _, m := range is { sum += m() } if sum != 0+2+4+6+8 { println("wrong sum, expected ", 20, ", saw ", sum) bug = true } if bug { panic("for_esc_method") } }
tools/go/ssa/interp/testdata/forvarlifetime_go122.go/0
{ "file_path": "tools/go/ssa/interp/testdata/forvarlifetime_go122.go", "repo_id": "tools", "token_count": 3000 }
711
// 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. // Test for slice to array pointer conversion introduced in go1.17 // See: https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer package main func main() { s := make([]byte, 2, 4) if s0 := (*[0]byte)(s); s0 == nil { panic("converted from non-nil slice result in nil array pointer") } if s2 := (*[2]byte)(s); &s2[0] != &s[0] { panic("the converted array is not slice underlying array") } wantPanic( func() { _ = (*[4]byte)(s) // panics: len([4]byte) > len(s) }, "runtime error: array length is greater than slice length", ) var t []string if t0 := (*[0]string)(t); t0 != nil { panic("nil slice converted to *[0]byte should be nil") } wantPanic( func() { _ = (*[1]string)(t) // panics: len([1]string) > len(t) }, "runtime error: array length is greater than slice length", ) f() } type arr [2]int func f() { s := []int{1, 2, 3, 4} _ = *(*arr)(s) } func wantPanic(fn func(), s string) { defer func() { err := recover() if err == nil { panic("expected panic") } if got := err.(error).Error(); got != s { panic("expected panic " + s + " got " + got) } }() fn() }
tools/go/ssa/interp/testdata/slice2arrayptr.go/0
{ "file_path": "tools/go/ssa/interp/testdata/slice2arrayptr.go", "repo_id": "tools", "token_count": 509 }
712
package utf8 func DecodeRuneInString(string) (rune, int) func DecodeRune(b []byte) (rune, int) { return DecodeRuneInString(string(b)) } const RuneError = '\uFFFD'
tools/go/ssa/interp/testdata/src/unicode/utf8/utf8.go/0
{ "file_path": "tools/go/ssa/interp/testdata/src/unicode/utf8/utf8.go", "repo_id": "tools", "token_count": 70 }
713
// 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 package defines a high-level intermediate representation for // Go programs using static single-assignment (SSA) form. import ( "fmt" "go/ast" "go/constant" "go/token" "go/types" "sync" "golang.org/x/tools/go/types/typeutil" "golang.org/x/tools/internal/typeparams" ) // A Program is a partial or complete Go program converted to SSA form. type Program struct { Fset *token.FileSet // position information for the files of this Program imported map[string]*Package // all importable Packages, keyed by import path packages map[*types.Package]*Package // all created Packages mode BuilderMode // set of mode bits for SSA construction MethodSets typeutil.MethodSetCache // cache of type-checker's method-sets canon *canonizer // type canonicalization map ctxt *types.Context // cache for type checking instantiations methodsMu sync.Mutex methodSets typeutil.Map // maps type to its concrete *methodSet // memoization of whether a type refers to type parameters hasParamsMu sync.Mutex hasParams typeparams.Free runtimeTypesMu sync.Mutex runtimeTypes typeutil.Map // set of runtime types (from MakeInterface) // objectMethods is a memoization of objectMethod // to avoid creation of duplicate methods from type information. objectMethodsMu sync.Mutex objectMethods map[*types.Func]*Function } // A Package is a single analyzed Go package containing Members for // all package-level functions, variables, constants and types it // declares. These may be accessed directly via Members, or via the // type-specific accessor methods Func, Type, Var and Const. // // Members also contains entries for "init" (the synthetic package // initializer) and "init#%d", the nth declared init function, // and unspecified other things too. type Package struct { Prog *Program // the owning program Pkg *types.Package // the corresponding go/types.Package Members map[string]Member // all package members keyed by name (incl. init and init#%d) objects map[types.Object]Member // mapping of package objects to members (incl. methods). Contains *NamedConst, *Global, *Function (values but not types) init *Function // Func("init"); the package's init function debug bool // include full debug info in this package syntax bool // package was loaded from syntax // The following fields are set transiently, then cleared // after building. buildOnce sync.Once // ensures package building occurs once ninit int32 // number of init functions info *types.Info // package type information files []*ast.File // package ASTs created []*Function // members created as a result of building this package (includes declared functions, wrappers) initVersion map[ast.Expr]string // goversion to use for each global var init expr } // A Member is a member of a Go package, implemented by *NamedConst, // *Global, *Function, or *Type; they are created by package-level // const, var, func and type declarations respectively. type Member interface { Name() string // declared name of the package member String() string // package-qualified name of the package member RelString(*types.Package) string // like String, but relative refs are unqualified Object() types.Object // typechecker's object for this member, if any Pos() token.Pos // position of member's declaration, if known Type() types.Type // type of the package member Token() token.Token // token.{VAR,FUNC,CONST,TYPE} Package() *Package // the containing package } // A Type is a Member of a Package representing a package-level named type. type Type struct { object *types.TypeName pkg *Package } // A NamedConst is a Member of a Package representing a package-level // named constant. // // Pos() returns the position of the declaring ast.ValueSpec.Names[*] // identifier. // // NB: a NamedConst is not a Value; it contains a constant Value, which // it augments with the name and position of its 'const' declaration. type NamedConst struct { object *types.Const Value *Const pkg *Package } // A Value is an SSA value that can be referenced by an instruction. type Value interface { // Name returns the name of this value, and determines how // this Value appears when used as an operand of an // Instruction. // // This is the same as the source name for Parameters, // Builtins, Functions, FreeVars, Globals. // For constants, it is a representation of the constant's value // and type. For all other Values this is the name of the // virtual register defined by the instruction. // // The name of an SSA Value is not semantically significant, // and may not even be unique within a function. Name() string // If this value is an Instruction, String returns its // disassembled form; otherwise it returns unspecified // human-readable information about the Value, such as its // kind, name and type. String() string // Type returns the type of this value. Many instructions // (e.g. IndexAddr) change their behaviour depending on the // types of their operands. Type() types.Type // Parent returns the function to which this Value belongs. // It returns nil for named Functions, Builtin, Const and Global. Parent() *Function // Referrers returns the list of instructions that have this // value as one of their operands; it may contain duplicates // if an instruction has a repeated operand. // // Referrers actually returns a pointer through which the // caller may perform mutations to the object's state. // // Referrers is currently only defined if Parent()!=nil, // i.e. for the function-local values FreeVar, Parameter, // Functions (iff anonymous) and all value-defining instructions. // It returns nil for named Functions, Builtin, Const and Global. // // Instruction.Operands contains the inverse of this relation. Referrers() *[]Instruction // Pos returns the location of the AST token most closely // associated with the operation that gave rise to this value, // or token.NoPos if it was not explicit in the source. // // For each ast.Node type, a particular token is designated as // the closest location for the expression, e.g. the Lparen // for an *ast.CallExpr. This permits a compact but // approximate mapping from Values to source positions for use // in diagnostic messages, for example. // // (Do not use this position to determine which Value // corresponds to an ast.Expr; use Function.ValueForExpr // instead. NB: it requires that the function was built with // debug information.) Pos() token.Pos } // An Instruction is an SSA instruction that computes a new Value or // has some effect. // // An Instruction that defines a value (e.g. BinOp) also implements // the Value interface; an Instruction that only has an effect (e.g. Store) // does not. type Instruction interface { // String returns the disassembled form of this value. // // Examples of Instructions that are Values: // "x + y" (BinOp) // "len([])" (Call) // Note that the name of the Value is not printed. // // Examples of Instructions that are not Values: // "return x" (Return) // "*y = x" (Store) // // (The separation Value.Name() from Value.String() is useful // for some analyses which distinguish the operation from the // value it defines, e.g., 'y = local int' is both an allocation // of memory 'local int' and a definition of a pointer y.) String() string // Parent returns the function to which this instruction // belongs. Parent() *Function // Block returns the basic block to which this instruction // belongs. Block() *BasicBlock // setBlock sets the basic block to which this instruction belongs. setBlock(*BasicBlock) // Operands returns the operands of this instruction: the // set of Values it references. // // Specifically, it appends their addresses to rands, a // user-provided slice, and returns the resulting slice, // permitting avoidance of memory allocation. // // The operands are appended in undefined order, but the order // is consistent for a given Instruction; the addresses are // always non-nil but may point to a nil Value. Clients may // store through the pointers, e.g. to effect a value // renaming. // // Value.Referrers is a subset of the inverse of this // relation. (Referrers are not tracked for all types of // Values.) Operands(rands []*Value) []*Value // Pos returns the location of the AST token most closely // associated with the operation that gave rise to this // instruction, or token.NoPos if it was not explicit in the // source. // // For each ast.Node type, a particular token is designated as // the closest location for the expression, e.g. the Go token // for an *ast.GoStmt. This permits a compact but approximate // mapping from Instructions to source positions for use in // diagnostic messages, for example. // // (Do not use this position to determine which Instruction // corresponds to an ast.Expr; see the notes for Value.Pos. // This position may be used to determine which non-Value // Instruction corresponds to some ast.Stmts, but not all: If // and Jump instructions have no Pos(), for example.) Pos() token.Pos } // A Node is a node in the SSA value graph. Every concrete type that // implements Node is also either a Value, an Instruction, or both. // // Node contains the methods common to Value and Instruction, plus the // Operands and Referrers methods generalized to return nil for // non-Instructions and non-Values, respectively. // // Node is provided to simplify SSA graph algorithms. Clients should // use the more specific and informative Value or Instruction // interfaces where appropriate. type Node interface { // Common methods: String() string Pos() token.Pos Parent() *Function // Partial methods: Operands(rands []*Value) []*Value // nil for non-Instructions Referrers() *[]Instruction // nil for non-Values } // Function represents the parameters, results, and code of a function // or method. // // If Blocks is nil, this indicates an external function for which no // Go source code is available. In this case, FreeVars, Locals, and // Params are nil too. Clients performing whole-program analysis must // handle external functions specially. // // Blocks contains the function's control-flow graph (CFG). // Blocks[0] is the function entry point; block order is not otherwise // semantically significant, though it may affect the readability of // the disassembly. // To iterate over the blocks in dominance order, use DomPreorder(). // // Recover is an optional second entry point to which control resumes // after a recovered panic. The Recover block may contain only a return // statement, preceded by a load of the function's named return // parameters, if any. // // A nested function (Parent()!=nil) that refers to one or more // lexically enclosing local variables ("free variables") has FreeVars. // Such functions cannot be called directly but require a // value created by MakeClosure which, via its Bindings, supplies // values for these parameters. // // If the function is a method (Signature.Recv() != nil) then the first // element of Params is the receiver parameter. // // A Go package may declare many functions called "init". // For each one, Object().Name() returns "init" but Name() returns // "init#1", etc, in declaration order. // // Pos() returns the declaring ast.FuncLit.Type.Func or the position // of the ast.FuncDecl.Name, if the function was explicit in the // source. Synthetic wrappers, for which Synthetic != "", may share // the same position as the function they wrap. // Syntax.Pos() always returns the position of the declaring "func" token. // // When the operand of a range statement is an iterator function, // the loop body is transformed into a synthetic anonymous function // that is passed as the yield argument in a call to the iterator. // In that case, Function.Pos is the position of the "range" token, // and Function.Syntax is the ast.RangeStmt. // // Synthetic functions, for which Synthetic != "", are functions // that do not appear in the source AST. These include: // - method wrappers, // - thunks, // - bound functions, // - empty functions built from loaded type information, // - yield functions created from range-over-func loops, // - package init functions, and // - instantiations of generic functions. // // Synthetic wrapper functions may share the same position // as the function they wrap. // // Type() returns the function's Signature. // // A generic function is a function or method that has uninstantiated type // parameters (TypeParams() != nil). Consider a hypothetical generic // method, (*Map[K,V]).Get. It may be instantiated with all // non-parameterized types as (*Map[string,int]).Get or with // parameterized types as (*Map[string,U]).Get, where U is a type parameter. // In both instantiations, Origin() refers to the instantiated generic // method, (*Map[K,V]).Get, TypeParams() refers to the parameters [K,V] of // the generic method. TypeArgs() refers to [string,U] or [string,int], // respectively, and is nil in the generic method. type Function struct { name string object *types.Func // symbol for declared function (nil for FuncLit or synthetic init) method *selection // info about provenance of synthetic methods; thunk => non-nil Signature *types.Signature pos token.Pos // source information Synthetic string // provenance of synthetic function; "" for true source functions syntax ast.Node // *ast.Func{Decl,Lit}, if from syntax (incl. generic instances) or (*ast.RangeStmt if a yield function) info *types.Info // type annotations (iff syntax != nil) goversion string // Go version of syntax (NB: init is special) parent *Function // enclosing function if anon; nil if global Pkg *Package // enclosing package; nil for shared funcs (wrappers and error.Error) Prog *Program // enclosing program buildshared *task // wait for a shared function to be done building (may be nil if <=1 builder ever needs to wait) // These fields are populated only when the function body is built: Params []*Parameter // function parameters; for methods, includes receiver FreeVars []*FreeVar // free variables whose values must be supplied by closure Locals []*Alloc // frame-allocated variables of this function Blocks []*BasicBlock // basic blocks of the function; nil => external Recover *BasicBlock // optional; control transfers here after recovered panic AnonFuncs []*Function // anonymous functions (from FuncLit,RangeStmt) directly beneath this one referrers []Instruction // referring instructions (iff Parent() != nil) anonIdx int32 // position of a nested function in parent's AnonFuncs. fn.Parent()!=nil => fn.Parent().AnonFunc[fn.anonIdx] == fn. typeparams *types.TypeParamList // type parameters of this function. typeparams.Len() > 0 => generic or instance of generic function typeargs []types.Type // type arguments that instantiated typeparams. len(typeargs) > 0 => instance of generic function topLevelOrigin *Function // the origin function if this is an instance of a source function. nil if Parent()!=nil. generic *generic // instances of this function, if generic // The following fields are cleared after building. build buildFunc // algorithm to build function body (nil => built) currentBlock *BasicBlock // where to emit code vars map[*types.Var]Value // addresses of local variables results []*Alloc // result allocations of the current function returnVars []*types.Var // variables for a return statement. Either results or for range-over-func a parent's results targets *targets // linked stack of branch targets lblocks map[*types.Label]*lblock // labelled blocks subst *subster // type parameter substitutions (if non-nil) jump *types.Var // synthetic variable for the yield state (non-nil => range-over-func) deferstack *types.Var // synthetic variable holding enclosing ssa:deferstack() source *Function // nearest enclosing source function exits []*exit // exits of the function that need to be resolved uniq int64 // source of unique ints within the source tree while building } // BasicBlock represents an SSA basic block. // // The final element of Instrs is always an explicit transfer of // control (If, Jump, Return, or Panic). // // A block may contain no Instructions only if it is unreachable, // i.e., Preds is nil. Empty blocks are typically pruned. // // BasicBlocks and their Preds/Succs relation form a (possibly cyclic) // graph independent of the SSA Value graph: the control-flow graph or // CFG. It is illegal for multiple edges to exist between the same // pair of blocks. // // Each BasicBlock is also a node in the dominator tree of the CFG. // The tree may be navigated using Idom()/Dominees() and queried using // Dominates(). // // The order of Preds and Succs is significant (to Phi and If // instructions, respectively). type BasicBlock struct { Index int // index of this block within Parent().Blocks Comment string // optional label; no semantic significance parent *Function // parent function Instrs []Instruction // instructions in order Preds, Succs []*BasicBlock // predecessors and successors succs2 [2]*BasicBlock // initial space for Succs dom domInfo // dominator tree info gaps int // number of nil Instrs (transient) rundefers int // number of rundefers (transient) } // Pure values ---------------------------------------- // A FreeVar represents a free variable of the function to which it // belongs. // // FreeVars are used to implement anonymous functions, whose free // variables are lexically captured in a closure formed by // MakeClosure. The value of such a free var is an Alloc or another // FreeVar and is considered a potentially escaping heap address, with // pointer type. // // FreeVars are also used to implement bound method closures. Such a // free var represents the receiver value and may be of any type that // has concrete methods. // // Pos() returns the position of the value that was captured, which // belongs to an enclosing function. type FreeVar struct { name string typ types.Type pos token.Pos parent *Function referrers []Instruction // Transiently needed during building. outer Value // the Value captured from the enclosing context. } // A Parameter represents an input parameter of a function. type Parameter struct { name string object *types.Var // non-nil typ types.Type parent *Function referrers []Instruction } // A Const represents a value known at build time. // // Consts include true constants of boolean, numeric, and string types, as // defined by the Go spec; these are represented by a non-nil Value field. // // Consts also include the "zero" value of any type, of which the nil values // of various pointer-like types are a special case; these are represented // by a nil Value field. // // Pos() returns token.NoPos. // // Example printed forms: // // 42:int // "hello":untyped string // 3+4i:MyComplex // nil:*int // nil:[]string // [3]int{}:[3]int // struct{x string}{}:struct{x string} // 0:interface{int|int64} // nil:interface{bool|int} // no go/constant representation type Const struct { typ types.Type Value constant.Value } // A Global is a named Value holding the address of a package-level // variable. // // Pos() returns the position of the ast.ValueSpec.Names[*] // identifier. type Global struct { name string object types.Object // a *types.Var; may be nil for synthetics e.g. init$guard typ types.Type pos token.Pos Pkg *Package } // A Builtin represents a specific use of a built-in function, e.g. len. // // Builtins are immutable values. Builtins do not have addresses. // Builtins can only appear in CallCommon.Value. // // Name() indicates the function: one of the built-in functions from the // Go spec (excluding "make" and "new") or one of these ssa-defined // intrinsics: // // // wrapnilchk returns ptr if non-nil, panics otherwise. // // (For use in indirection wrappers.) // func ssa:wrapnilchk(ptr *T, recvType, methodName string) *T // // Object() returns a *types.Builtin for built-ins defined by the spec, // nil for others. // // Type() returns a *types.Signature representing the effective // signature of the built-in for this call. type Builtin struct { name string sig *types.Signature } // Value-defining instructions ---------------------------------------- // The Alloc instruction reserves space for a variable of the given type, // zero-initializes it, and yields its address. // // Alloc values are always addresses, and have pointer types, so the // type of the allocated variable is actually // Type().Underlying().(*types.Pointer).Elem(). // // If Heap is false, Alloc zero-initializes the same local variable in // the call frame and returns its address; in this case the Alloc must // be present in Function.Locals. We call this a "local" alloc. // // If Heap is true, Alloc allocates a new zero-initialized variable // each time the instruction is executed. We call this a "new" alloc. // // When Alloc is applied to a channel, map or slice type, it returns // the address of an uninitialized (nil) reference of that kind; store // the result of MakeSlice, MakeMap or MakeChan in that location to // instantiate these types. // // Pos() returns the ast.CompositeLit.Lbrace for a composite literal, // or the ast.CallExpr.Rparen for a call to new() or for a call that // allocates a varargs slice. // // Example printed form: // // t0 = local int // t1 = new int type Alloc struct { register Comment string Heap bool index int // dense numbering; for lifting } // The Phi instruction represents an SSA φ-node, which combines values // that differ across incoming control-flow edges and yields a new // value. Within a block, all φ-nodes must appear before all non-φ // nodes. // // Pos() returns the position of the && or || for short-circuit // control-flow joins, or that of the *Alloc for φ-nodes inserted // during SSA renaming. // // Example printed form: // // t2 = phi [0: t0, 1: t1] type Phi struct { register Comment string // a hint as to its purpose Edges []Value // Edges[i] is value for Block().Preds[i] } // The Call instruction represents a function or method call. // // The Call instruction yields the function result if there is exactly // one. Otherwise it returns a tuple, the components of which are // accessed via Extract. // // See CallCommon for generic function call documentation. // // Pos() returns the ast.CallExpr.Lparen, if explicit in the source. // // Example printed form: // // t2 = println(t0, t1) // t4 = t3() // t7 = invoke t5.Println(...t6) type Call struct { register Call CallCommon } // The BinOp instruction yields the result of binary operation X Op Y. // // Pos() returns the ast.BinaryExpr.OpPos, if explicit in the source. // // Example printed form: // // t1 = t0 + 1:int type BinOp struct { register // One of: // ADD SUB MUL QUO REM + - * / % // AND OR XOR SHL SHR AND_NOT & | ^ << >> &^ // EQL NEQ LSS LEQ GTR GEQ == != < <= < >= Op token.Token X, Y Value } // The UnOp instruction yields the result of Op X. // ARROW is channel receive. // MUL is pointer indirection (load). // XOR is bitwise complement. // SUB is negation. // NOT is logical negation. // // If CommaOk and Op=ARROW, the result is a 2-tuple of the value above // and a boolean indicating the success of the receive. The // components of the tuple are accessed using Extract. // // Pos() returns the ast.UnaryExpr.OpPos, if explicit in the source. // For receive operations (ARROW) implicit in ranging over a channel, // Pos() returns the ast.RangeStmt.For. // For implicit memory loads (STAR), Pos() returns the position of the // most closely associated source-level construct; the details are not // specified. // // Example printed form: // // t0 = *x // t2 = <-t1,ok type UnOp struct { register Op token.Token // One of: NOT SUB ARROW MUL XOR ! - <- * ^ X Value CommaOk bool } // The ChangeType instruction applies to X a value-preserving type // change to Type(). // // Type changes are permitted: // - between a named type and its underlying type. // - between two named types of the same underlying type. // - between (possibly named) pointers to identical base types. // - from a bidirectional channel to a read- or write-channel, // optionally adding/removing a name. // - between a type (t) and an instance of the type (tσ), i.e. // Type() == σ(X.Type()) (or X.Type()== σ(Type())) where // σ is the type substitution of Parent().TypeParams by // Parent().TypeArgs. // // This operation cannot fail dynamically. // // Type changes may to be to or from a type parameter (or both). All // types in the type set of X.Type() have a value-preserving type // change to all types in the type set of Type(). // // Pos() returns the ast.CallExpr.Lparen, if the instruction arose // from an explicit conversion in the source. // // Example printed form: // // t1 = changetype *int <- IntPtr (t0) type ChangeType struct { register X Value } // The Convert instruction yields the conversion of value X to type // Type(). One or both of those types is basic (but possibly named). // // A conversion may change the value and representation of its operand. // Conversions are permitted: // - between real numeric types. // - between complex numeric types. // - between string and []byte or []rune. // - between pointers and unsafe.Pointer. // - between unsafe.Pointer and uintptr. // - from (Unicode) integer to (UTF-8) string. // // A conversion may imply a type name change also. // // Conversions may to be to or from a type parameter. All types in // the type set of X.Type() can be converted to all types in the type // set of Type(). // // This operation cannot fail dynamically. // // Conversions of untyped string/number/bool constants to a specific // representation are eliminated during SSA construction. // // Pos() returns the ast.CallExpr.Lparen, if the instruction arose // from an explicit conversion in the source. // // Example printed form: // // t1 = convert []byte <- string (t0) type Convert struct { register X Value } // The MultiConvert instruction yields the conversion of value X to type // Type(). Either X.Type() or Type() must be a type parameter. Each // type in the type set of X.Type() can be converted to each type in the // type set of Type(). // // See the documentation for Convert, ChangeType, and SliceToArrayPointer // for the conversions that are permitted. Additionally conversions of // slices to arrays are permitted. // // This operation can fail dynamically (see SliceToArrayPointer). // // Pos() returns the ast.CallExpr.Lparen, if the instruction arose // from an explicit conversion in the source. // // Example printed form: // // t1 = multiconvert D <- S (t0) [*[2]rune <- []rune | string <- []rune] type MultiConvert struct { register X Value from []*types.Term to []*types.Term } // ChangeInterface constructs a value of one interface type from a // value of another interface type known to be assignable to it. // This operation cannot fail. // // Pos() returns the ast.CallExpr.Lparen if the instruction arose from // an explicit T(e) conversion; the ast.TypeAssertExpr.Lparen if the // instruction arose from an explicit e.(T) operation; or token.NoPos // otherwise. // // Example printed form: // // t1 = change interface interface{} <- I (t0) type ChangeInterface struct { register X Value } // The SliceToArrayPointer instruction yields the conversion of slice X to // array pointer. // // Pos() returns the ast.CallExpr.Lparen, if the instruction arose // from an explicit conversion in the source. // // Conversion may to be to or from a type parameter. All types in // the type set of X.Type() must be a slice types that can be converted to // all types in the type set of Type() which must all be pointer to array // types. // // This operation can fail dynamically if the length of the slice is less // than the length of the array. // // Example printed form: // // t1 = slice to array pointer *[4]byte <- []byte (t0) type SliceToArrayPointer struct { register X Value } // MakeInterface constructs an instance of an interface type from a // value of a concrete type. // // Use Program.MethodSets.MethodSet(X.Type()) to find the method-set // of X, and Program.MethodValue(m) to find the implementation of a method. // // To construct the zero value of an interface type T, use: // // NewConst(constant.MakeNil(), T, pos) // // Pos() returns the ast.CallExpr.Lparen, if the instruction arose // from an explicit conversion in the source. // // Example printed form: // // t1 = make interface{} <- int (42:int) // t2 = make Stringer <- t0 type MakeInterface struct { register X Value } // The MakeClosure instruction yields a closure value whose code is // Fn and whose free variables' values are supplied by Bindings. // // Type() returns a (possibly named) *types.Signature. // // Pos() returns the ast.FuncLit.Type.Func for a function literal // closure or the ast.SelectorExpr.Sel for a bound method closure. // // Example printed form: // // t0 = make closure anon@1.2 [x y z] // t1 = make closure bound$(main.I).add [i] type MakeClosure struct { register Fn Value // always a *Function Bindings []Value // values for each free variable in Fn.FreeVars } // The MakeMap instruction creates a new hash-table-based map object // and yields a value of kind map. // // Type() returns a (possibly named) *types.Map. // // Pos() returns the ast.CallExpr.Lparen, if created by make(map), or // the ast.CompositeLit.Lbrack if created by a literal. // // Example printed form: // // t1 = make map[string]int t0 // t1 = make StringIntMap t0 type MakeMap struct { register Reserve Value // initial space reservation; nil => default } // The MakeChan instruction creates a new channel object and yields a // value of kind chan. // // Type() returns a (possibly named) *types.Chan. // // Pos() returns the ast.CallExpr.Lparen for the make(chan) that // created it. // // Example printed form: // // t0 = make chan int 0 // t0 = make IntChan 0 type MakeChan struct { register Size Value // int; size of buffer; zero => synchronous. } // The MakeSlice instruction yields a slice of length Len backed by a // newly allocated array of length Cap. // // Both Len and Cap must be non-nil Values of integer type. // // (Alloc(types.Array) followed by Slice will not suffice because // Alloc can only create arrays of constant length.) // // Type() returns a (possibly named) *types.Slice. // // Pos() returns the ast.CallExpr.Lparen for the make([]T) that // created it. // // Example printed form: // // t1 = make []string 1:int t0 // t1 = make StringSlice 1:int t0 type MakeSlice struct { register Len Value Cap Value } // The Slice instruction yields a slice of an existing string, slice // or *array X between optional integer bounds Low and High. // // Dynamically, this instruction panics if X evaluates to a nil *array // pointer. // // Type() returns string if the type of X was string, otherwise a // *types.Slice with the same element type as X. // // Pos() returns the ast.SliceExpr.Lbrack if created by a x[:] slice // operation, the ast.CompositeLit.Lbrace if created by a literal, or // NoPos if not explicit in the source (e.g. a variadic argument slice). // // Example printed form: // // t1 = slice t0[1:] type Slice struct { register X Value // slice, string, or *array Low, High, Max Value // each may be nil } // The FieldAddr instruction yields the address of Field of *struct X. // // The field is identified by its index within the field list of the // struct type of X. // // Dynamically, this instruction panics if X evaluates to a nil // pointer. // // Type() returns a (possibly named) *types.Pointer. // // Pos() returns the position of the ast.SelectorExpr.Sel for the // field, if explicit in the source. For implicit selections, returns // the position of the inducing explicit selection. If produced for a // struct literal S{f: e}, it returns the position of the colon; for // S{e} it returns the start of expression e. // // Example printed form: // // t1 = &t0.name [#1] type FieldAddr struct { register X Value // *struct Field int // index into CoreType(CoreType(X.Type()).(*types.Pointer).Elem()).(*types.Struct).Fields } // The Field instruction yields the Field of struct X. // // The field is identified by its index within the field list of the // struct type of X; by using numeric indices we avoid ambiguity of // package-local identifiers and permit compact representations. // // Pos() returns the position of the ast.SelectorExpr.Sel for the // field, if explicit in the source. For implicit selections, returns // the position of the inducing explicit selection. // Example printed form: // // t1 = t0.name [#1] type Field struct { register X Value // struct Field int // index into CoreType(X.Type()).(*types.Struct).Fields } // The IndexAddr instruction yields the address of the element at // index Index of collection X. Index is an integer expression. // // The elements of maps and strings are not addressable; use Lookup (map), // Index (string), or MapUpdate instead. // // Dynamically, this instruction panics if X evaluates to a nil *array // pointer. // // Type() returns a (possibly named) *types.Pointer. // // Pos() returns the ast.IndexExpr.Lbrack for the index operation, if // explicit in the source. // // Example printed form: // // t2 = &t0[t1] type IndexAddr struct { register X Value // *array, slice or type parameter with types array, *array, or slice. Index Value // numeric index } // The Index instruction yields element Index of collection X, an array, // string or type parameter containing an array, a string, a pointer to an, // array or a slice. // // Pos() returns the ast.IndexExpr.Lbrack for the index operation, if // explicit in the source. // // Example printed form: // // t2 = t0[t1] type Index struct { register X Value // array, string or type parameter with types array, *array, slice, or string. Index Value // integer index } // The Lookup instruction yields element Index of collection map X. // Index is the appropriate key type. // // If CommaOk, the result is a 2-tuple of the value above and a // boolean indicating the result of a map membership test for the key. // The components of the tuple are accessed using Extract. // // Pos() returns the ast.IndexExpr.Lbrack, if explicit in the source. // // Example printed form: // // t2 = t0[t1] // t5 = t3[t4],ok type Lookup struct { register X Value // map Index Value // key-typed index CommaOk bool // return a value,ok pair } // SelectState is a helper for Select. // It represents one goal state and its corresponding communication. type SelectState struct { Dir types.ChanDir // direction of case (SendOnly or RecvOnly) Chan Value // channel to use (for send or receive) Send Value // value to send (for send) Pos token.Pos // position of token.ARROW DebugNode ast.Node // ast.SendStmt or ast.UnaryExpr(<-) [debug mode] } // The Select instruction tests whether (or blocks until) one // of the specified sent or received states is entered. // // Let n be the number of States for which Dir==RECV and T_i (0<=i<n) // be the element type of each such state's Chan. // Select returns an n+2-tuple // // (index int, recvOk bool, r_0 T_0, ... r_n-1 T_n-1) // // The tuple's components, described below, must be accessed via the // Extract instruction. // // If Blocking, select waits until exactly one state holds, i.e. a // channel becomes ready for the designated operation of sending or // receiving; select chooses one among the ready states // pseudorandomly, performs the send or receive operation, and sets // 'index' to the index of the chosen channel. // // If !Blocking, select doesn't block if no states hold; instead it // returns immediately with index equal to -1. // // If the chosen channel was used for a receive, the r_i component is // set to the received value, where i is the index of that state among // all n receive states; otherwise r_i has the zero value of type T_i. // Note that the receive index i is not the same as the state // index index. // // The second component of the triple, recvOk, is a boolean whose value // is true iff the selected operation was a receive and the receive // successfully yielded a value. // // Pos() returns the ast.SelectStmt.Select. // // Example printed form: // // t3 = select nonblocking [<-t0, t1<-t2] // t4 = select blocking [] type Select struct { register States []*SelectState Blocking bool } // The Range instruction yields an iterator over the domain and range // of X, which must be a string or map. // // Elements are accessed via Next. // // Type() returns an opaque and degenerate "rangeIter" type. // // Pos() returns the ast.RangeStmt.For. // // Example printed form: // // t0 = range "hello":string type Range struct { register X Value // string or map } // The Next instruction reads and advances the (map or string) // iterator Iter and returns a 3-tuple value (ok, k, v). If the // iterator is not exhausted, ok is true and k and v are the next // elements of the domain and range, respectively. Otherwise ok is // false and k and v are undefined. // // Components of the tuple are accessed using Extract. // // The IsString field distinguishes iterators over strings from those // over maps, as the Type() alone is insufficient: consider // map[int]rune. // // Type() returns a *types.Tuple for the triple (ok, k, v). // The types of k and/or v may be types.Invalid. // // Example printed form: // // t1 = next t0 type Next struct { register Iter Value IsString bool // true => string iterator; false => map iterator. } // The TypeAssert instruction tests whether interface value X has type // AssertedType. // // If !CommaOk, on success it returns v, the result of the conversion // (defined below); on failure it panics. // // If CommaOk: on success it returns a pair (v, true) where v is the // result of the conversion; on failure it returns (z, false) where z // is AssertedType's zero value. The components of the pair must be // accessed using the Extract instruction. // // If Underlying: tests whether interface value X has the underlying // type AssertedType. // // If AssertedType is a concrete type, TypeAssert checks whether the // dynamic type in interface X is equal to it, and if so, the result // of the conversion is a copy of the value in the interface. // // If AssertedType is an interface, TypeAssert checks whether the // dynamic type of the interface is assignable to it, and if so, the // result of the conversion is a copy of the interface value X. // If AssertedType is a superinterface of X.Type(), the operation will // fail iff the operand is nil. (Contrast with ChangeInterface, which // performs no nil-check.) // // Type() reflects the actual type of the result, possibly a // 2-types.Tuple; AssertedType is the asserted type. // // Depending on the TypeAssert's purpose, Pos may return: // - the ast.CallExpr.Lparen of an explicit T(e) conversion; // - the ast.TypeAssertExpr.Lparen of an explicit e.(T) operation; // - the ast.CaseClause.Case of a case of a type-switch statement; // - the Ident(m).NamePos of an interface method value i.m // (for which TypeAssert may be used to effect the nil check). // // Example printed form: // // t1 = typeassert t0.(int) // t3 = typeassert,ok t2.(T) type TypeAssert struct { register X Value AssertedType types.Type CommaOk bool } // The Extract instruction yields component Index of Tuple. // // This is used to access the results of instructions with multiple // return values, such as Call, TypeAssert, Next, UnOp(ARROW) and // IndexExpr(Map). // // Example printed form: // // t1 = extract t0 #1 type Extract struct { register Tuple Value Index int } // Instructions executed for effect. They do not yield a value. -------------------- // The Jump instruction transfers control to the sole successor of its // owning block. // // A Jump must be the last instruction of its containing BasicBlock. // // Pos() returns NoPos. // // Example printed form: // // jump done type Jump struct { anInstruction } // The If instruction transfers control to one of the two successors // of its owning block, depending on the boolean Cond: the first if // true, the second if false. // // An If instruction must be the last instruction of its containing // BasicBlock. // // Pos() returns NoPos. // // Example printed form: // // if t0 goto done else body type If struct { anInstruction Cond Value } // The Return instruction returns values and control back to the calling // function. // // len(Results) is always equal to the number of results in the // function's signature. // // If len(Results) > 1, Return returns a tuple value with the specified // components which the caller must access using Extract instructions. // // There is no instruction to return a ready-made tuple like those // returned by a "value,ok"-mode TypeAssert, Lookup or UnOp(ARROW) or // a tail-call to a function with multiple result parameters. // // Return must be the last instruction of its containing BasicBlock. // Such a block has no successors. // // Pos() returns the ast.ReturnStmt.Return, if explicit in the source. // // Example printed form: // // return // return nil:I, 2:int type Return struct { anInstruction Results []Value pos token.Pos } // The RunDefers instruction pops and invokes the entire stack of // procedure calls pushed by Defer instructions in this function. // // It is legal to encounter multiple 'rundefers' instructions in a // single control-flow path through a function; this is useful in // the combined init() function, for example. // // Pos() returns NoPos. // // Example printed form: // // rundefers type RunDefers struct { anInstruction } // The Panic instruction initiates a panic with value X. // // A Panic instruction must be the last instruction of its containing // BasicBlock, which must have no successors. // // NB: 'go panic(x)' and 'defer panic(x)' do not use this instruction; // they are treated as calls to a built-in function. // // Pos() returns the ast.CallExpr.Lparen if this panic was explicit // in the source. // // Example printed form: // // panic t0 type Panic struct { anInstruction X Value // an interface{} pos token.Pos } // The Go instruction creates a new goroutine and calls the specified // function within it. // // See CallCommon for generic function call documentation. // // Pos() returns the ast.GoStmt.Go. // // Example printed form: // // go println(t0, t1) // go t3() // go invoke t5.Println(...t6) type Go struct { anInstruction Call CallCommon pos token.Pos } // The Defer instruction pushes the specified call onto a stack of // functions to be called by a RunDefers instruction or by a panic. // // If DeferStack != nil, it indicates the defer list that the defer is // added to. Defer list values come from the Builtin function // ssa:deferstack. Calls to ssa:deferstack() produces the defer stack // of the current function frame. DeferStack allows for deferring into an // alternative function stack than the current function. // // See CallCommon for generic function call documentation. // // Pos() returns the ast.DeferStmt.Defer. // // Example printed form: // // defer println(t0, t1) // defer t3() // defer invoke t5.Println(...t6) type Defer struct { anInstruction Call CallCommon DeferStack Value // stack of deferred functions (from ssa:deferstack() intrinsic) onto which this function is pushed pos token.Pos } // The Send instruction sends X on channel Chan. // // Pos() returns the ast.SendStmt.Arrow, if explicit in the source. // // Example printed form: // // send t0 <- t1 type Send struct { anInstruction Chan, X Value pos token.Pos } // The Store instruction stores Val at address Addr. // Stores can be of arbitrary types. // // Pos() returns the position of the source-level construct most closely // associated with the memory store operation. // Since implicit memory stores are numerous and varied and depend upon // implementation choices, the details are not specified. // // Example printed form: // // *x = y type Store struct { anInstruction Addr Value Val Value pos token.Pos } // The MapUpdate instruction updates the association of Map[Key] to // Value. // // Pos() returns the ast.KeyValueExpr.Colon or ast.IndexExpr.Lbrack, // if explicit in the source. // // Example printed form: // // t0[t1] = t2 type MapUpdate struct { anInstruction Map Value Key Value Value Value pos token.Pos } // A DebugRef instruction maps a source-level expression Expr to the // SSA value X that represents the value (!IsAddr) or address (IsAddr) // of that expression. // // DebugRef is a pseudo-instruction: it has no dynamic effect. // // Pos() returns Expr.Pos(), the start position of the source-level // expression. This is not the same as the "designated" token as // documented at Value.Pos(). e.g. CallExpr.Pos() does not return the // position of the ("designated") Lparen token. // // If Expr is an *ast.Ident denoting a var or func, Object() returns // the object; though this information can be obtained from the type // checker, including it here greatly facilitates debugging. // For non-Ident expressions, Object() returns nil. // // DebugRefs are generated only for functions built with debugging // enabled; see Package.SetDebugMode() and the GlobalDebug builder // mode flag. // // DebugRefs are not emitted for ast.Idents referring to constants or // predeclared identifiers, since they are trivial and numerous. // Nor are they emitted for ast.ParenExprs. // // (By representing these as instructions, rather than out-of-band, // consistency is maintained during transformation passes by the // ordinary SSA renaming machinery.) // // Example printed form: // // ; *ast.CallExpr @ 102:9 is t5 // ; var x float64 @ 109:72 is x // ; address of *ast.CompositeLit @ 216:10 is t0 type DebugRef struct { // TODO(generics): Reconsider what DebugRefs are for generics. anInstruction Expr ast.Expr // the referring expression (never *ast.ParenExpr) object types.Object // the identity of the source var/func IsAddr bool // Expr is addressable and X is the address it denotes X Value // the value or address of Expr } // Embeddable mix-ins and helpers for common parts of other structs. ----------- // register is a mix-in embedded by all SSA values that are also // instructions, i.e. virtual registers, and provides a uniform // implementation of most of the Value interface: Value.Name() is a // numbered register (e.g. "t0"); the other methods are field accessors. // // Temporary names are automatically assigned to each register on // completion of building a function in SSA form. // // Clients must not assume that the 'id' value (and the Name() derived // from it) is unique within a function. As always in this API, // semantics are determined only by identity; names exist only to // facilitate debugging. type register struct { anInstruction num int // "name" of virtual register, e.g. "t0". Not guaranteed unique. typ types.Type // type of virtual register pos token.Pos // position of source expression, or NoPos referrers []Instruction } // anInstruction is a mix-in embedded by all Instructions. // It provides the implementations of the Block and setBlock methods. type anInstruction struct { block *BasicBlock // the basic block of this instruction } // CallCommon is contained by Go, Defer and Call to hold the // common parts of a function or method call. // // Each CallCommon exists in one of two modes, function call and // interface method invocation, or "call" and "invoke" for short. // // 1. "call" mode: when Method is nil (!IsInvoke), a CallCommon // represents an ordinary function call of the value in Value, // which may be a *Builtin, a *Function or any other value of kind // 'func'. // // Value may be one of: // // (a) a *Function, indicating a statically dispatched call // to a package-level function, an anonymous function, or // a method of a named type. // (b) a *MakeClosure, indicating an immediately applied // function literal with free variables. // (c) a *Builtin, indicating a statically dispatched call // to a built-in function. // (d) any other value, indicating a dynamically dispatched // function call. // // StaticCallee returns the identity of the callee in cases // (a) and (b), nil otherwise. // // Args contains the arguments to the call. If Value is a method, // Args[0] contains the receiver parameter. // // Example printed form: // // t2 = println(t0, t1) // go t3() // defer t5(...t6) // // 2. "invoke" mode: when Method is non-nil (IsInvoke), a CallCommon // represents a dynamically dispatched call to an interface method. // In this mode, Value is the interface value and Method is the // interface's abstract method. The interface value may be a type // parameter. Note: an interface method may be shared by multiple // interfaces due to embedding; Value.Type() provides the specific // interface used for this call. // // Value is implicitly supplied to the concrete method implementation // as the receiver parameter; in other words, Args[0] holds not the // receiver but the first true argument. // // Example printed form: // // t1 = invoke t0.String() // go invoke t3.Run(t2) // defer invoke t4.Handle(...t5) // // For all calls to variadic functions (Signature().Variadic()), // the last element of Args is a slice. type CallCommon struct { Value Value // receiver (invoke mode) or func value (call mode) Method *types.Func // interface method (invoke mode) Args []Value // actual parameters (in static method call, includes receiver) pos token.Pos // position of CallExpr.Lparen, iff explicit in source } // IsInvoke returns true if this call has "invoke" (not "call") mode. func (c *CallCommon) IsInvoke() bool { return c.Method != nil } func (c *CallCommon) Pos() token.Pos { return c.pos } // Signature returns the signature of the called function. // // For an "invoke"-mode call, the signature of the interface method is // returned. // // In either "call" or "invoke" mode, if the callee is a method, its // receiver is represented by sig.Recv, not sig.Params().At(0). func (c *CallCommon) Signature() *types.Signature { if c.Method != nil { return c.Method.Type().(*types.Signature) } return typeparams.CoreType(c.Value.Type()).(*types.Signature) } // StaticCallee returns the callee if this is a trivially static // "call"-mode call to a function. func (c *CallCommon) StaticCallee() *Function { switch fn := c.Value.(type) { case *Function: return fn case *MakeClosure: return fn.Fn.(*Function) } return nil } // Description returns a description of the mode of this call suitable // for a user interface, e.g., "static method call". func (c *CallCommon) Description() string { switch fn := c.Value.(type) { case *Builtin: return "built-in function call" case *MakeClosure: return "static function closure call" case *Function: if fn.Signature.Recv() != nil { return "static method call" } return "static function call" } if c.IsInvoke() { return "dynamic method call" // ("invoke" mode) } return "dynamic function call" } // The CallInstruction interface, implemented by *Go, *Defer and *Call, // exposes the common parts of function-calling instructions, // yet provides a way back to the Value defined by *Call alone. type CallInstruction interface { Instruction Common() *CallCommon // returns the common parts of the call Value() *Call // returns the result value of the call (*Call) or nil (*Go, *Defer) } func (s *Call) Common() *CallCommon { return &s.Call } func (s *Defer) Common() *CallCommon { return &s.Call } func (s *Go) Common() *CallCommon { return &s.Call } func (s *Call) Value() *Call { return s } func (s *Defer) Value() *Call { return nil } func (s *Go) Value() *Call { return nil } func (v *Builtin) Type() types.Type { return v.sig } func (v *Builtin) Name() string { return v.name } func (*Builtin) Referrers() *[]Instruction { return nil } func (v *Builtin) Pos() token.Pos { return token.NoPos } func (v *Builtin) Object() types.Object { return types.Universe.Lookup(v.name) } func (v *Builtin) Parent() *Function { return nil } func (v *FreeVar) Type() types.Type { return v.typ } func (v *FreeVar) Name() string { return v.name } func (v *FreeVar) Referrers() *[]Instruction { return &v.referrers } func (v *FreeVar) Pos() token.Pos { return v.pos } func (v *FreeVar) Parent() *Function { return v.parent } func (v *Global) Type() types.Type { return v.typ } func (v *Global) Name() string { return v.name } func (v *Global) Parent() *Function { return nil } func (v *Global) Pos() token.Pos { return v.pos } func (v *Global) Referrers() *[]Instruction { return nil } func (v *Global) Token() token.Token { return token.VAR } func (v *Global) Object() types.Object { return v.object } func (v *Global) String() string { return v.RelString(nil) } func (v *Global) Package() *Package { return v.Pkg } func (v *Global) RelString(from *types.Package) string { return relString(v, from) } func (v *Function) Name() string { return v.name } func (v *Function) Type() types.Type { return v.Signature } func (v *Function) Pos() token.Pos { return v.pos } func (v *Function) Token() token.Token { return token.FUNC } func (v *Function) Object() types.Object { if v.object != nil { return types.Object(v.object) } return nil } func (v *Function) String() string { return v.RelString(nil) } func (v *Function) Package() *Package { return v.Pkg } func (v *Function) Parent() *Function { return v.parent } func (v *Function) Referrers() *[]Instruction { if v.parent != nil { return &v.referrers } return nil } // TypeParams are the function's type parameters if generic or the // type parameters that were instantiated if fn is an instantiation. func (fn *Function) TypeParams() *types.TypeParamList { return fn.typeparams } // TypeArgs are the types that TypeParams() were instantiated by to create fn // from fn.Origin(). func (fn *Function) TypeArgs() []types.Type { return fn.typeargs } // Origin returns the generic function from which fn was instantiated, // or nil if fn is not an instantiation. func (fn *Function) Origin() *Function { if fn.parent != nil && len(fn.typeargs) > 0 { // Nested functions are BUILT at a different time than their instances. // Build declared package if not yet BUILT. This is not an expected use // case, but is simple and robust. fn.declaredPackage().Build() } return origin(fn) } // origin is the function that fn is an instantiation of. Returns nil if fn is // not an instantiation. // // Precondition: fn and the origin function are done building. func origin(fn *Function) *Function { if fn.parent != nil && len(fn.typeargs) > 0 { return origin(fn.parent).AnonFuncs[fn.anonIdx] } return fn.topLevelOrigin } func (v *Parameter) Type() types.Type { return v.typ } func (v *Parameter) Name() string { return v.name } func (v *Parameter) Object() types.Object { return v.object } func (v *Parameter) Referrers() *[]Instruction { return &v.referrers } func (v *Parameter) Pos() token.Pos { return v.object.Pos() } func (v *Parameter) Parent() *Function { return v.parent } func (v *Alloc) Type() types.Type { return v.typ } func (v *Alloc) Referrers() *[]Instruction { return &v.referrers } func (v *Alloc) Pos() token.Pos { return v.pos } func (v *register) Type() types.Type { return v.typ } func (v *register) setType(typ types.Type) { v.typ = typ } func (v *register) Name() string { return fmt.Sprintf("t%d", v.num) } func (v *register) setNum(num int) { v.num = num } func (v *register) Referrers() *[]Instruction { return &v.referrers } func (v *register) Pos() token.Pos { return v.pos } func (v *register) setPos(pos token.Pos) { v.pos = pos } func (v *anInstruction) Parent() *Function { return v.block.parent } func (v *anInstruction) Block() *BasicBlock { return v.block } func (v *anInstruction) setBlock(block *BasicBlock) { v.block = block } func (v *anInstruction) Referrers() *[]Instruction { return nil } func (t *Type) Name() string { return t.object.Name() } func (t *Type) Pos() token.Pos { return t.object.Pos() } func (t *Type) Type() types.Type { return t.object.Type() } func (t *Type) Token() token.Token { return token.TYPE } func (t *Type) Object() types.Object { return t.object } func (t *Type) String() string { return t.RelString(nil) } func (t *Type) Package() *Package { return t.pkg } func (t *Type) RelString(from *types.Package) string { return relString(t, from) } func (c *NamedConst) Name() string { return c.object.Name() } func (c *NamedConst) Pos() token.Pos { return c.object.Pos() } func (c *NamedConst) String() string { return c.RelString(nil) } func (c *NamedConst) Type() types.Type { return c.object.Type() } func (c *NamedConst) Token() token.Token { return token.CONST } func (c *NamedConst) Object() types.Object { return c.object } func (c *NamedConst) Package() *Package { return c.pkg } func (c *NamedConst) RelString(from *types.Package) string { return relString(c, from) } func (d *DebugRef) Object() types.Object { return d.object } // Func returns the package-level function of the specified name, // or nil if not found. func (p *Package) Func(name string) (f *Function) { f, _ = p.Members[name].(*Function) return } // Var returns the package-level variable of the specified name, // or nil if not found. func (p *Package) Var(name string) (g *Global) { g, _ = p.Members[name].(*Global) return } // Const returns the package-level constant of the specified name, // or nil if not found. func (p *Package) Const(name string) (c *NamedConst) { c, _ = p.Members[name].(*NamedConst) return } // Type returns the package-level type of the specified name, // or nil if not found. func (p *Package) Type(name string) (t *Type) { t, _ = p.Members[name].(*Type) return } func (v *Call) Pos() token.Pos { return v.Call.pos } func (s *Defer) Pos() token.Pos { return s.pos } func (s *Go) Pos() token.Pos { return s.pos } func (s *MapUpdate) Pos() token.Pos { return s.pos } func (s *Panic) Pos() token.Pos { return s.pos } func (s *Return) Pos() token.Pos { return s.pos } func (s *Send) Pos() token.Pos { return s.pos } func (s *Store) Pos() token.Pos { return s.pos } func (s *If) Pos() token.Pos { return token.NoPos } func (s *Jump) Pos() token.Pos { return token.NoPos } func (s *RunDefers) Pos() token.Pos { return token.NoPos } func (s *DebugRef) Pos() token.Pos { return s.Expr.Pos() } // Operands. func (v *Alloc) Operands(rands []*Value) []*Value { return rands } func (v *BinOp) Operands(rands []*Value) []*Value { return append(rands, &v.X, &v.Y) } func (c *CallCommon) Operands(rands []*Value) []*Value { rands = append(rands, &c.Value) for i := range c.Args { rands = append(rands, &c.Args[i]) } return rands } func (s *Go) Operands(rands []*Value) []*Value { return s.Call.Operands(rands) } func (s *Call) Operands(rands []*Value) []*Value { return s.Call.Operands(rands) } func (s *Defer) Operands(rands []*Value) []*Value { return append(s.Call.Operands(rands), &s.DeferStack) } func (v *ChangeInterface) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *ChangeType) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *Convert) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *MultiConvert) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *SliceToArrayPointer) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (s *DebugRef) Operands(rands []*Value) []*Value { return append(rands, &s.X) } func (v *Extract) Operands(rands []*Value) []*Value { return append(rands, &v.Tuple) } func (v *Field) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *FieldAddr) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (s *If) Operands(rands []*Value) []*Value { return append(rands, &s.Cond) } func (v *Index) Operands(rands []*Value) []*Value { return append(rands, &v.X, &v.Index) } func (v *IndexAddr) Operands(rands []*Value) []*Value { return append(rands, &v.X, &v.Index) } func (*Jump) Operands(rands []*Value) []*Value { return rands } func (v *Lookup) Operands(rands []*Value) []*Value { return append(rands, &v.X, &v.Index) } func (v *MakeChan) Operands(rands []*Value) []*Value { return append(rands, &v.Size) } func (v *MakeClosure) Operands(rands []*Value) []*Value { rands = append(rands, &v.Fn) for i := range v.Bindings { rands = append(rands, &v.Bindings[i]) } return rands } func (v *MakeInterface) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *MakeMap) Operands(rands []*Value) []*Value { return append(rands, &v.Reserve) } func (v *MakeSlice) Operands(rands []*Value) []*Value { return append(rands, &v.Len, &v.Cap) } func (v *MapUpdate) Operands(rands []*Value) []*Value { return append(rands, &v.Map, &v.Key, &v.Value) } func (v *Next) Operands(rands []*Value) []*Value { return append(rands, &v.Iter) } func (s *Panic) Operands(rands []*Value) []*Value { return append(rands, &s.X) } func (v *Phi) Operands(rands []*Value) []*Value { for i := range v.Edges { rands = append(rands, &v.Edges[i]) } return rands } func (v *Range) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (s *Return) Operands(rands []*Value) []*Value { for i := range s.Results { rands = append(rands, &s.Results[i]) } return rands } func (*RunDefers) Operands(rands []*Value) []*Value { return rands } func (v *Select) Operands(rands []*Value) []*Value { for i := range v.States { rands = append(rands, &v.States[i].Chan, &v.States[i].Send) } return rands } func (s *Send) Operands(rands []*Value) []*Value { return append(rands, &s.Chan, &s.X) } func (v *Slice) Operands(rands []*Value) []*Value { return append(rands, &v.X, &v.Low, &v.High, &v.Max) } func (s *Store) Operands(rands []*Value) []*Value { return append(rands, &s.Addr, &s.Val) } func (v *TypeAssert) Operands(rands []*Value) []*Value { return append(rands, &v.X) } func (v *UnOp) Operands(rands []*Value) []*Value { return append(rands, &v.X) } // Non-Instruction Values: func (v *Builtin) Operands(rands []*Value) []*Value { return rands } func (v *FreeVar) Operands(rands []*Value) []*Value { return rands } func (v *Const) Operands(rands []*Value) []*Value { return rands } func (v *Function) Operands(rands []*Value) []*Value { return rands } func (v *Global) Operands(rands []*Value) []*Value { return rands } func (v *Parameter) Operands(rands []*Value) []*Value { return rands }
tools/go/ssa/ssa.go/0
{ "file_path": "tools/go/ssa/ssa.go", "repo_id": "tools", "token_count": 20673 }
714
package bytes func Compare(a, b []byte) int
tools/go/ssa/testdata/src/bytes/bytes.go/0
{ "file_path": "tools/go/ssa/testdata/src/bytes/bytes.go", "repo_id": "tools", "token_count": 15 }
715
package atomic import "unsafe" func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
tools/go/ssa/testdata/src/sync/atomic/atomic.go/0
{ "file_path": "tools/go/ssa/testdata/src/sync/atomic/atomic.go", "repo_id": "tools", "token_count": 32 }
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" "sort" "golang.org/x/tools/go/types/typeutil" ) func ExampleMap() { const source = `package P var X []string var Y []string const p, q = 1.0, 2.0 func f(offset int32) (value byte, ok bool) func g(rune) (uint8, bool) ` // Parse and type-check the package. fset := token.NewFileSet() f, err := parser.ParseFile(fset, "P.go", source, 0) if err != nil { panic(err) } pkg, err := new(types.Config).Check("P", fset, []*ast.File{f}, nil) if err != nil { panic(err) } scope := pkg.Scope() // Group names of package-level objects by their type. var namesByType typeutil.Map // value is []string for _, name := range scope.Names() { T := scope.Lookup(name).Type() names, _ := namesByType.At(T).([]string) names = append(names, name) namesByType.Set(T, names) } // Format, sort, and print the map entries. var lines []string namesByType.Iterate(func(T types.Type, names any) { lines = append(lines, fmt.Sprintf("%s %s", names, T)) }) sort.Strings(lines) for _, line := range lines { fmt.Println(line) } // Output: // [X Y] []string // [f g] func(offset int32) (value byte, ok bool) // [p q] untyped float }
tools/go/types/typeutil/example_test.go/0
{ "file_path": "tools/go/types/typeutil/example_test.go", "repo_id": "tools", "token_count": 557 }
717
// 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. //go:build go1.7 // +build go1.7 package godoc import ( "bytes" "fmt" "testing" ) // Verify that scanIdentifier isn't quadratic. // This doesn't actually measure and fail on its own, but it was previously // very obvious when running by hand. // // TODO: if there's a reliable and non-flaky way to test this, do so. // Maybe count user CPU time instead of wall time? But that's not easy // to do portably in Go. func TestStructField(t *testing.T) { for _, n := range []int{10, 100, 1000, 10000} { n := n t.Run(fmt.Sprint(n), func(t *testing.T) { var buf bytes.Buffer fmt.Fprintf(&buf, "package foo\n\ntype T struct {\n") for i := 0; i < n; i++ { fmt.Fprintf(&buf, "\t// Field%d is foo.\n\tField%d int\n\n", i, i) } fmt.Fprintf(&buf, "}\n") linkifySource(t, buf.Bytes()) }) } }
tools/godoc/godoc17_test.go/0
{ "file_path": "tools/godoc/godoc17_test.go", "repo_id": "tools", "token_count": 372 }
718
// 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. package godoc // This file contains the mechanism to "linkify" html source // text containing EBNF sections (as found in go_spec.html). // The result is the input source text with the EBNF sections // modified such that identifiers are linked to the respective // definitions. import ( "bytes" "fmt" "io" "text/scanner" ) type ebnfParser struct { out io.Writer // parser output src []byte // parser input scanner scanner.Scanner prev int // offset of previous token pos int // offset of current token tok rune // one token look-ahead lit string // token literal } func (p *ebnfParser) flush() { p.out.Write(p.src[p.prev:p.pos]) p.prev = p.pos } func (p *ebnfParser) next() { p.tok = p.scanner.Scan() p.pos = p.scanner.Position.Offset p.lit = p.scanner.TokenText() } func (p *ebnfParser) printf(format string, args ...interface{}) { p.flush() fmt.Fprintf(p.out, format, args...) } func (p *ebnfParser) errorExpected(msg string) { p.printf(`<span class="highlight">error: expected %s, found %s</span>`, msg, scanner.TokenString(p.tok)) } func (p *ebnfParser) expect(tok rune) { if p.tok != tok { p.errorExpected(scanner.TokenString(tok)) } p.next() // make progress in any case } func (p *ebnfParser) parseIdentifier(def bool) { if p.tok == scanner.Ident { name := p.lit if def { p.printf(`<a id="%s">%s</a>`, name, name) } else { p.printf(`<a href="#%s" class="noline">%s</a>`, name, name) } p.prev += len(name) // skip identifier when printing next time p.next() } else { p.expect(scanner.Ident) } } func (p *ebnfParser) parseTerm() bool { switch p.tok { case scanner.Ident: p.parseIdentifier(false) case scanner.String, scanner.RawString: p.next() const ellipsis = '…' // U+2026, the horizontal ellipsis character if p.tok == ellipsis { p.next() p.expect(scanner.String) } case '(': p.next() p.parseExpression() p.expect(')') case '[': p.next() p.parseExpression() p.expect(']') case '{': p.next() p.parseExpression() p.expect('}') default: return false // no term found } return true } func (p *ebnfParser) parseSequence() { if !p.parseTerm() { p.errorExpected("term") } for p.parseTerm() { } } func (p *ebnfParser) parseExpression() { for { p.parseSequence() if p.tok != '|' { break } p.next() } } func (p *ebnfParser) parseProduction() { p.parseIdentifier(true) p.expect('=') if p.tok != '.' { p.parseExpression() } p.expect('.') } func (p *ebnfParser) parse(out io.Writer, src []byte) { // initialize ebnfParser p.out = out p.src = src p.scanner.Init(bytes.NewBuffer(src)) p.next() // initializes pos, tok, lit // process source for p.tok != scanner.EOF { p.parseProduction() } p.flush() } // Markers around EBNF sections var ( openTag = []byte(`<pre class="ebnf">`) closeTag = []byte(`</pre>`) ) func Linkify(out io.Writer, src []byte) { for len(src) > 0 { // i: beginning of EBNF text (or end of source) i := bytes.Index(src, openTag) if i < 0 { i = len(src) - len(openTag) } i += len(openTag) // j: end of EBNF text (or end of source) j := bytes.Index(src[i:], closeTag) // close marker if j < 0 { j = len(src) - i } j += i // write text before EBNF out.Write(src[0:i]) // process EBNF var p ebnfParser p.parse(out, src[i:j]) // advance src = src[j:] } }
tools/godoc/spec.go/0
{ "file_path": "tools/godoc/spec.go", "repo_id": "tools", "token_count": 1501 }
719
// 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. /* In the absence of any formal way to specify interfaces in JavaScript, here's a skeleton implementation of a playground transport. function Transport() { // Set up any transport state (eg, make a websocket connection). return { Run: function(body, output, options) { // Compile and run the program 'body' with 'options'. // Call the 'output' callback to display program output. return { Kill: function() { // Kill the running program. } }; } }; } // The output callback is called multiple times, and each time it is // passed an object of this form. var write = { Kind: 'string', // 'start', 'stdout', 'stderr', 'end' Body: 'string' // content of write or end status message } // The first call must be of Kind 'start' with no body. // Subsequent calls may be of Kind 'stdout' or 'stderr' // and must have a non-null Body string. // The final call should be of Kind 'end' with an optional // Body string, signifying a failure ("killed", for example). // The output callback must be of this form. // See PlaygroundOutput (below) for an implementation. function outputCallback(write) { } */ // HTTPTransport is the default transport. // enableVet enables running vet if a program was compiled and ran successfully. // If vet returned any errors, display them before the output of a program. function HTTPTransport(enableVet) { 'use strict'; function playback(output, data) { // Backwards compatibility: default values do not affect the output. var events = data.Events || []; var errors = data.Errors || ''; var status = data.Status || 0; var isTest = data.IsTest || false; var testsFailed = data.TestsFailed || 0; var timeout; output({ Kind: 'start' }); function next() { if (!events || events.length === 0) { if (isTest) { if (testsFailed > 0) { output({ Kind: 'system', Body: '\n' + testsFailed + ' test' + (testsFailed > 1 ? 's' : '') + ' failed.', }); } else { output({ Kind: 'system', Body: '\nAll tests passed.' }); } } else { if (status > 0) { output({ Kind: 'end', Body: 'status ' + status + '.' }); } else { if (errors !== '') { // errors are displayed only in the case of timeout. output({ Kind: 'end', Body: errors + '.' }); } else { output({ Kind: 'end' }); } } } return; } var e = events.shift(); if (e.Delay === 0) { output({ Kind: e.Kind, Body: e.Message }); next(); return; } timeout = setTimeout(function() { output({ Kind: e.Kind, Body: e.Message }); next(); }, e.Delay / 1000000); } next(); return { Stop: function() { clearTimeout(timeout); }, }; } function error(output, msg) { output({ Kind: 'start' }); output({ Kind: 'stderr', Body: msg }); output({ Kind: 'end' }); } function buildFailed(output, msg) { output({ Kind: 'start' }); output({ Kind: 'stderr', Body: msg }); output({ Kind: 'system', Body: '\nGo build failed.' }); } var seq = 0; return { Run: function(body, output, options) { seq++; var cur = seq; var playing; $.ajax('/compile', { type: 'POST', data: { version: 2, body: body, withVet: enableVet }, dataType: 'json', success: function(data) { if (seq != cur) return; if (!data) return; if (playing != null) playing.Stop(); if (data.Errors) { if (data.Errors === 'process took too long') { // Playback the output that was captured before the timeout. playing = playback(output, data); } else { buildFailed(output, data.Errors); } return; } if (!data.Events) { data.Events = []; } if (data.VetErrors) { // Inject errors from the vet as the first events in the output. data.Events.unshift({ Message: 'Go vet exited.\n\n', Kind: 'system', Delay: 0, }); data.Events.unshift({ Message: data.VetErrors, Kind: 'stderr', Delay: 0, }); } if (!enableVet || data.VetOK || data.VetErrors) { playing = playback(output, data); return; } // In case the server support doesn't support // compile+vet in same request signaled by the // 'withVet' parameter above, also try the old way. // TODO: remove this when it falls out of use. // It is 2019-05-13 now. $.ajax('/vet', { data: { body: body }, type: 'POST', dataType: 'json', success: function(dataVet) { if (dataVet.Errors) { // inject errors from the vet as the first events in the output data.Events.unshift({ Message: 'Go vet exited.\n\n', Kind: 'system', Delay: 0, }); data.Events.unshift({ Message: dataVet.Errors, Kind: 'stderr', Delay: 0, }); } playing = playback(output, data); }, error: function() { playing = playback(output, data); }, }); }, error: function() { error(output, 'Error communicating with remote server.'); }, }); return { Kill: function() { if (playing != null) playing.Stop(); output({ Kind: 'end', Body: 'killed' }); }, }; }, }; } function SocketTransport() { 'use strict'; var id = 0; var outputs = {}; var started = {}; var websocket; if (window.location.protocol == 'http:') { websocket = new WebSocket('ws://' + window.location.host + '/socket'); } else if (window.location.protocol == 'https:') { websocket = new WebSocket('wss://' + window.location.host + '/socket'); } websocket.onclose = function() { console.log('websocket connection closed'); }; websocket.onmessage = function(e) { var m = JSON.parse(e.data); var output = outputs[m.Id]; if (output === null) return; if (!started[m.Id]) { output({ Kind: 'start' }); started[m.Id] = true; } output({ Kind: m.Kind, Body: m.Body }); }; function send(m) { websocket.send(JSON.stringify(m)); } return { Run: function(body, output, options) { var thisID = id + ''; id++; outputs[thisID] = output; send({ Id: thisID, Kind: 'run', Body: body, Options: options }); return { Kill: function() { send({ Id: thisID, Kind: 'kill' }); }, }; }, }; } function PlaygroundOutput(el) { 'use strict'; return function(write) { if (write.Kind == 'start') { el.innerHTML = ''; return; } var cl = 'system'; if (write.Kind == 'stdout' || write.Kind == 'stderr') cl = write.Kind; var m = write.Body; if (write.Kind == 'end') { m = '\nProgram exited' + (m ? ': ' + m : '.'); } if (m.indexOf('IMAGE:') === 0) { // TODO(adg): buffer all writes before creating image var url = 'data:image/png;base64,' + m.substr(6); var img = document.createElement('img'); img.src = url; el.appendChild(img); return; } // ^L clears the screen. var s = m.split('\x0c'); if (s.length > 1) { el.innerHTML = ''; m = s.pop(); } m = m.replace(/&/g, '&amp;'); m = m.replace(/</g, '&lt;'); m = m.replace(/>/g, '&gt;'); var needScroll = el.scrollTop + el.offsetHeight == el.scrollHeight; var span = document.createElement('span'); span.className = cl; span.innerHTML = m; el.appendChild(span); if (needScroll) el.scrollTop = el.scrollHeight - el.offsetHeight; }; } (function() { function lineHighlight(error) { var regex = /prog.go:([0-9]+)/g; var r = regex.exec(error); while (r) { $('.lines div') .eq(r[1] - 1) .addClass('lineerror'); r = regex.exec(error); } } function highlightOutput(wrappedOutput) { return function(write) { if (write.Body) lineHighlight(write.Body); wrappedOutput(write); }; } function lineClear() { $('.lineerror').removeClass('lineerror'); } // opts is an object with these keys // codeEl - code editor element // outputEl - program output element // runEl - run button element // fmtEl - fmt button element (optional) // fmtImportEl - fmt "imports" checkbox element (optional) // shareEl - share button element (optional) // shareURLEl - share URL text input element (optional) // shareRedirect - base URL to redirect to on share (optional) // toysEl - toys select element (optional) // enableHistory - enable using HTML5 history API (optional) // transport - playground transport to use (default is HTTPTransport) // enableShortcuts - whether to enable shortcuts (Ctrl+S/Cmd+S to save) (default is false) // enableVet - enable running vet and displaying its errors function playground(opts) { var code = $(opts.codeEl); var transport = opts['transport'] || new HTTPTransport(opts['enableVet']); var running; // autoindent helpers. function insertTabs(n) { // find the selection start and end var start = code[0].selectionStart; var end = code[0].selectionEnd; // split the textarea content into two, and insert n tabs var v = code[0].value; var u = v.substr(0, start); for (var i = 0; i < n; i++) { u += '\t'; } u += v.substr(end); // set revised content code[0].value = u; // reset caret position after inserted tabs code[0].selectionStart = start + n; code[0].selectionEnd = start + n; } function autoindent(el) { var curpos = el.selectionStart; var tabs = 0; while (curpos > 0) { curpos--; if (el.value[curpos] == '\t') { tabs++; } else if (tabs > 0 || el.value[curpos] == '\n') { break; } } setTimeout(function() { insertTabs(tabs); }, 1); } // NOTE(cbro): e is a jQuery event, not a DOM event. function handleSaveShortcut(e) { if (e.isDefaultPrevented()) return false; if (!e.metaKey && !e.ctrlKey) return false; if (e.key != 'S' && e.key != 's') return false; e.preventDefault(); // Share and save share(function(url) { window.location.href = url + '.go?download=true'; }); return true; } function keyHandler(e) { if (opts.enableShortcuts && handleSaveShortcut(e)) return; if (e.keyCode == 9 && !e.ctrlKey) { // tab (but not ctrl-tab) insertTabs(1); e.preventDefault(); return false; } if (e.keyCode == 13) { // enter if (e.shiftKey) { // +shift run(); e.preventDefault(); return false; } if (e.ctrlKey) { // +control fmt(); e.preventDefault(); } else { autoindent(e.target); } } return true; } code.unbind('keydown').bind('keydown', keyHandler); var outdiv = $(opts.outputEl).empty(); var output = $('<pre/>').appendTo(outdiv); function body() { return $(opts.codeEl).val(); } function setBody(text) { $(opts.codeEl).val(text); } function origin(href) { return ('' + href) .split('/') .slice(0, 3) .join('/'); } var pushedEmpty = window.location.pathname == '/'; function inputChanged() { if (pushedEmpty) { return; } pushedEmpty = true; $(opts.shareURLEl).hide(); window.history.pushState(null, '', '/'); } function popState(e) { if (e === null) { return; } if (e && e.state && e.state.code) { setBody(e.state.code); } } var rewriteHistory = false; if ( window.history && window.history.pushState && window.addEventListener && opts.enableHistory ) { rewriteHistory = true; code[0].addEventListener('input', inputChanged); window.addEventListener('popstate', popState); } function setError(error) { if (running) running.Kill(); lineClear(); lineHighlight(error); output .empty() .addClass('error') .text(error); } function loading() { lineClear(); if (running) running.Kill(); output.removeClass('error').text('Waiting for remote server...'); } function run() { loading(); running = transport.Run( body(), highlightOutput(PlaygroundOutput(output[0])) ); } function fmt() { loading(); var data = { body: body() }; if ($(opts.fmtImportEl).is(':checked')) { data['imports'] = 'true'; } $.ajax('/fmt', { data: data, type: 'POST', dataType: 'json', success: function(data) { if (data.Error) { setError(data.Error); } else { setBody(data.Body); setError(''); } }, }); } var shareURL; // jQuery element to show the shared URL. var sharing = false; // true if there is a pending request. var shareCallbacks = []; function share(opt_callback) { if (opt_callback) shareCallbacks.push(opt_callback); if (sharing) return; sharing = true; var sharingData = body(); $.ajax('https://play.golang.org/share', { processData: false, data: sharingData, type: 'POST', contentType: 'text/plain; charset=utf-8', complete: function(xhr) { sharing = false; if (xhr.status != 200) { alert('Server error; try again.'); return; } if (opts.shareRedirect) { window.location = opts.shareRedirect + xhr.responseText; } var path = '/p/' + xhr.responseText; var url = origin(window.location) + path; for (var i = 0; i < shareCallbacks.length; i++) { shareCallbacks[i](url); } shareCallbacks = []; if (shareURL) { shareURL .show() .val(url) .focus() .select(); if (rewriteHistory) { var historyData = { code: sharingData }; window.history.pushState(historyData, '', path); pushedEmpty = false; } } }, }); } $(opts.runEl).click(run); $(opts.fmtEl).click(fmt); if ( opts.shareEl !== null && (opts.shareURLEl !== null || opts.shareRedirect !== null) ) { if (opts.shareURLEl) { shareURL = $(opts.shareURLEl).hide(); } $(opts.shareEl).click(function() { share(); }); } if (opts.toysEl !== null) { $(opts.toysEl).bind('change', function() { var toy = $(this).val(); $.ajax('/doc/play/' + toy, { processData: false, type: 'GET', complete: function(xhr) { if (xhr.status != 200) { alert('Server error; try again.'); return; } setBody(xhr.responseText); }, }); }); } } window.playground = playground; })();
tools/godoc/static/playground.js/0
{ "file_path": "tools/godoc/static/playground.js", "repo_id": "tools", "token_count": 7775 }
720
// 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 gatefs_test import ( "os" "runtime" "testing" "golang.org/x/tools/godoc/vfs" "golang.org/x/tools/godoc/vfs/gatefs" ) func TestRootType(t *testing.T) { goPath := os.Getenv("GOPATH") var expectedType vfs.RootType if goPath == "" { expectedType = "" } else { expectedType = vfs.RootTypeGoPath } tests := []struct { path string fsType vfs.RootType }{ {runtime.GOROOT(), vfs.RootTypeGoRoot}, {goPath, expectedType}, {"/tmp/", ""}, } for _, item := range tests { fs := gatefs.New(vfs.OS(item.path), make(chan bool, 1)) if fs.RootType("path") != item.fsType { t.Errorf("unexpected fsType. Expected- %v, Got- %v", item.fsType, fs.RootType("path")) } } }
tools/godoc/vfs/gatefs/gatefs_test.go/0
{ "file_path": "tools/godoc/vfs/gatefs/gatefs_test.go", "repo_id": "tools", "token_count": 350 }
721
# Gopls: Using Emacs ## Installing `gopls` To use `gopls` with Emacs, you must first [install the `gopls` binary](../README.md#installation) and ensure that the directory containing the resulting binary (either `$(go env GOBIN)` or `$(go env GOPATH)/bin`) is in your `PATH`. ## Choosing an Emacs LSP client To use `gopls` with Emacs, you will need to choose and install an Emacs LSP client package. Two popular client packages are [LSP Mode] and [Eglot]. LSP Mode takes a batteries-included approach, with many integrations enabled “out of the box” and several additional behaviors provided by `lsp-mode` itself. Eglot takes a minimally-intrusive approach, focusing on smooth integration with other established packages. It provides a few of its own `eglot-` commands but no additional keybindings by default. Once you have selected which client you want to use, install it per the packages instructions: see [Eglot 1-2-3](https://github.com/joaotavora/eglot#1-2-3) or [LSP Mode Installation](https://emacs-lsp.github.io/lsp-mode/page/installation/). ## Common configuration Both Eglot and LSP Mode can integrate with popular packages in the Emacs ecosystem: * The built-in [`xref`] package provides cross-references. * The built-in [Flymake] package provides an on-the-fly diagnostic overlay. * [Company] mode displays code completion candidates (with a richer UI than the built-in [`completion-at-point`]). Eglot provides documentation using the built-in [ElDoc] minor mode, while LSP Mode by default provides documentation using its own [`lsp-ui`] mode. Eglot by default locates the project root using the [`project`] package. In LSP Mode, this behavior can be configured using the `lsp-auto-guess-root` setting. ## Configuring LSP Mode ### Loading LSP Mode in `.emacs` ```elisp (require 'lsp-mode) (add-hook 'go-mode-hook #'lsp-deferred) ;; Set up before-save hooks to format buffer and add/delete imports. ;; Make sure you don't have other gofmt/goimports hooks enabled. (defun lsp-go-install-save-hooks () (add-hook 'before-save-hook #'lsp-format-buffer t t) (add-hook 'before-save-hook #'lsp-organize-imports t t)) (add-hook 'go-mode-hook #'lsp-go-install-save-hooks) ``` ### Configuring `gopls` via LSP Mode See [settings] for information about available gopls settings. Stable gopls settings have corresponding configuration variables in `lsp-mode`. For example, `(setq lsp-gopls-use-placeholders nil)` will disable placeholders in completion snippets. See [`lsp-go`] for a list of available variables. Experimental settings can be configured via `lsp-register-custom-settings`: ```lisp (lsp-register-custom-settings '(("gopls.completeUnimported" t t) ("gopls.staticcheck" t t))) ``` Note that after changing settings you must restart gopls using e.g. `M-x lsp-restart-workspace`. ## Configuring Eglot ### Configuring `project` for Go modules in `.emacs` Eglot uses the built-in `project` package to identify the LSP workspace for a newly-opened buffer. The `project` package does not natively know about `GOPATH` or Go modules. Fortunately, you can give it a custom hook to tell it to look for the nearest parent `go.mod` file (that is, the root of the Go module) as the project root. ```elisp (require 'project) (defun project-find-go-module (dir) (when-let ((root (locate-dominating-file dir "go.mod"))) (cons 'go-module root))) (cl-defmethod project-root ((project (head go-module))) (cdr project)) (add-hook 'project-find-functions #'project-find-go-module) ``` ### Loading Eglot in `.emacs` ```elisp ;; Optional: load other packages before eglot to enable eglot integrations. (require 'company) (require 'yasnippet) (require 'go-mode) (require 'eglot) (add-hook 'go-mode-hook 'eglot-ensure) ;; Optional: install eglot-format-buffer as a save hook. ;; The depth of -10 places this before eglot's willSave notification, ;; so that that notification reports the actual contents that will be saved. (defun eglot-format-buffer-before-save () (add-hook 'before-save-hook #'eglot-format-buffer -10 t)) (add-hook 'go-mode-hook #'eglot-format-buffer-before-save) ``` Use `M-x eglot-upgrade-eglot` to upgrade to the latest version of Eglot. ### Configuring `gopls` via Eglot See [settings] for information about available gopls settings. LSP server settings are controlled by the `eglot-workspace-configuration` variable, which can be set either globally in `.emacs` or in a `.dir-locals.el` file in the project root. `.emacs`: ```elisp (setq-default eglot-workspace-configuration '((:gopls . ((staticcheck . t) (matcher . "CaseSensitive"))))) ``` `.dir-locals.el`: ```elisp ((nil (eglot-workspace-configuration . ((gopls . ((staticcheck . t) (matcher . "CaseSensitive"))))))) ``` ### Organizing imports with Eglot `gopls` provides the import-organizing functionality of `goimports` as an LSP code action, which you can invoke as needed by running `M-x eglot-code-actions` (or a key of your choice bound to the `eglot-code-actions` function) and selecting `Organize Imports` at the prompt. To automatically organize imports before saving, add a hook: ```elisp (add-hook 'before-save-hook (lambda () (call-interactively 'eglot-code-action-organize-imports)) nil t) ``` ## Troubleshooting Common errors: * When prompted by Emacs for your project folder, if you are using modules you must select the module's root folder (i.e. the directory with the "go.mod"). If you are using GOPATH, select your $GOPATH as your folder. * Emacs must have your environment set properly (PATH, GOPATH, etc). You can run `M-x getenv <RET> PATH <RET>` to see if your PATH is set in Emacs. If not, you can try starting Emacs from your terminal, using [this package][exec-path-from-shell], or moving your shell config from `.bashrc` into `.profile` and logging out and back in. * Make sure only one LSP client mode is installed. (For example, if using `lsp-mode`, ensure that you are not _also_ enabling `eglot`.) * Look for errors in the `*lsp-log*` buffer or run `M-x eglot-events-buffer`. * Ask for help in the `#emacs` channel on the [Gophers slack]. [LSP Mode]: https://emacs-lsp.github.io/lsp-mode/ [Eglot]: https://github.com/joaotavora/eglot/blob/master/README.md [`xref`]: https://www.gnu.org/software/emacs/manual/html_node/emacs/Xref.html [Flymake]: https://www.gnu.org/software/emacs/manual/html_node/flymake/Using-Flymake.html#Using-Flymake [Company]: https://company-mode.github.io/ [`completion-at-point`]: https://www.gnu.org/software/emacs/manual/html_node/elisp/Completion-in-Buffers.html [ElDoc]: https://elpa.gnu.org/packages/eldoc.html [`lsp-ui`]: https://emacs-lsp.github.io/lsp-ui/ [`lsp-go`]: https://github.com/emacs-lsp/lsp-mode/blob/master/clients/lsp-go.el [`use-package`]: https://github.com/jwiegley/use-package [`exec-path-from-shell`]: https://github.com/purcell/exec-path-from-shell [settings]: settings.md [Gophers slack]: https://invite.slack.golangbridge.org/
tools/gopls/doc/emacs.md/0
{ "file_path": "tools/gopls/doc/emacs.md", "repo_id": "tools", "token_count": 2349 }
722
<!-- this doc has been incorporated into features/transformation.md#Rename --> Gopls v0.14 supports a new refactoring operation: inlining of function calls. You can find it in VS Code by selecting a static call to a function or method f and choosing the `Refactor...` command followed by `Inline call to f`. Other editors and LSP clients have their own idiomatic command for it; for example, in Emacs with Eglot it is [`M-x eglot-code-action-inline`](https://joaotavora.github.io/eglot/#index-M_002dx-eglot_002dcode_002daction_002dinline) and in Vim with coc.nvim it is `coc-rename`. <!-- source code used for images: func six() int { return sum(1, 2, 3) } func sum(values ...int) int { total := 0 for _, v := range values { total += v } return total } --> ![Before: select Refactor... Inline call to sum](inline-before.png) ![After: the call has been replaced by the sum logic](inline-after.png) Inlining replaces the call expression by a copy of the function body, with parameters replaced by arguments. Inlining is useful for a number of reasons. Perhaps you want to eliminate a call to a deprecated function such as `ioutil.ReadFile` by replacing it with a call to the newer `os.ReadFile`; inlining will do that for you. Or perhaps you want to copy and modify an existing function in some way; inlining can provide a starting point. The inlining logic also provides a building block for other refactorings to come, such as "change signature". Not every call can be inlined. Of course, the tool needs to know which function is being called, so you can't inline a dynamic call through a function value or interface method; but static calls to methods are fine. Nor can you inline a call if the callee is declared in another package and refers to non-exported parts of that package, or to [internal packages](https://go.dev/doc/go1.4#internalpackages) that are inaccessible to the caller. When inlining is possible, it's critical that the tool preserve the original behavior of the program. We don't want refactoring to break the build, or, worse, to introduce subtle latent bugs. This is especially important when inlining tools are used to perform automated clean-ups in large code bases. We must be able to trust the tool. Our inliner is very careful not to make guesses or unsound assumptions about the behavior of the code. However, that does mean it sometimes produces a change that differs from what someone with expert knowledge of the same code might have written by hand. In the most difficult cases, especially with complex control flow, it may not be safe to eliminate the function call at all. For example, the behavior of a `defer` statement is intimately tied to its enclosing function call, and `defer` is the only control construct that can be used to handle panics, so it cannot be reduced into simpler constructs. So, for example, given a function f defined as: ```go func f(s string) { defer fmt.Println("goodbye") fmt.Println(s) } ``` a call `f("hello")` will be inlined to: ```go func() { defer fmt.Println("goodbye") fmt.Println("hello") }() ``` Although the parameter was eliminated, the function call remains. An inliner is a bit like an optimizing compiler. A compiler is considered "correct" if it doesn't change the meaning of the program in translation from source language to target language. An _optimizing_ compiler exploits the particulars of the input to generate better code, where "better" usually means more efficient. As users report inputs that cause the compiler to emit suboptimal code, the compiler is improved to recognize more cases, or more rules, and more exceptions to rules---but this process has no end. Inlining is similar, except that "better" code means tidier code. The most conservative translation provides a simple but (hopefully!) correct foundation, on top of which endless rules, and exceptions to rules, can embellish and improve the quality of the output. The following section lists some of the technical challenges involved in sound inlining: - **Effects:** When replacing a parameter by its argument expression, we must be careful not to change the effects of the call. For example, if we call a function `func twice(x int) int { return x + x }` with `twice(g())`, we do not want to see `g() + g()`, which would cause g's effects to occur twice, and potentially each call might return a different value. All effects must occur the same number of times, and in the same order. This requires analyzing both the arguments and the callee function to determine whether they are "pure", whether they read variables, or whether (and when) they update them too. The inliner will introduce a declaration such as `var x int = g()` when it cannot prove that it is safe to substitute the argument throughout. - **Constants:** If inlining always replaced a parameter by its argument when the value is constant, some programs would no longer build because checks previously done at run time would happen at compile time. For example `func index(s string, i int) byte { return s[i] }` is a valid function, but if inlining were to replace the call `index("abc", 3)` by the expression `"abc"[3]`, the compiler will report that the index `3` is out of bounds for the string `"abc"`. The inliner will prevent substitution of parameters by problematic constant arguments, again introducing a `var` declaration instead. - **Referential integrity:** When a parameter variable is replaced by its argument expression, we must ensure that any names in the argument expression continue to refer to the same thing---not to a different declaration in the callee function body that happens to use the same name! The inliner must replace local references such as `Printf` by qualified references such as `fmt.Printf`, and add an import of package `fmt` as needed. - **Implicit conversions:** When passing an argument to a function, it is implicitly converted to the parameter type. If we eliminate the parameter variable, we don't want to lose the conversion as it may be important. For example, in `func f(x any) { y := x; fmt.Printf("%T", &y) }` the type of variable y is `any`, so the program prints `"*interface{}"`. But if inlining the call `f(1)` were to produce the statement `y := 1`, then the type of y would have changed to `int`, which could cause a compile error or, as in this case, a bug, as the program now prints `"*int"`. When the inliner substitutes a parameter variable by its argument value, it may need to introduce explicit conversions of each value to the original parameter type, such as `y := any(1)`. - **Last reference:** When an argument expression has no effects and its corresponding parameter is never used, the expression may be eliminated. However, if the expression contains the last reference to a local variable at the caller, this may cause a compile error because the variable is now unused! So the inliner must be cautious about eliminating references to local variables. This is just a taste of the problem domain. If you're curious, the documentation for [golang.org/x/tools/internal/refactor/inline](https://pkg.go.dev/golang.org/x/tools/internal/refactor/inline) has more detail. All of this is to say, it's a complex problem, and we aim for correctness first of all. We've already implemented a number of important "tidiness optimizations" and we expect more to follow. Please give the inliner a try, and if you find any bugs (where the transformation is incorrect), please do report them. We'd also like to hear what "optimizations" you'd like to see next.
tools/gopls/doc/refactor-inline.md/0
{ "file_path": "tools/gopls/doc/refactor-inline.md", "repo_id": "tools", "token_count": 2002 }
723
// 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 main import ( "flag" "fmt" "io" "net/http" "os" "path" ) var bucket = flag.String("bucket", "golang-gopls_integration_tests", "GCS bucket holding test artifacts.") const usage = ` artifacts [--bucket=<bucket ID>] <cloud build evaluation ID> Fetch artifacts from an integration test run. Evaluation ID should be extracted from the cloud build notification. In order for this to work, the GCS bucket that artifacts were written to must be publicly readable. By default, this fetches from the golang-gopls_integration_tests bucket. ` func main() { flag.Usage = func() { fmt.Fprint(flag.CommandLine.Output(), usage) } flag.Parse() if flag.NArg() != 1 { flag.Usage() os.Exit(2) } evalID := flag.Arg(0) logURL := fmt.Sprintf("https://storage.googleapis.com/%s/log-%s.txt", *bucket, evalID) if err := download(logURL); err != nil { fmt.Fprintf(os.Stderr, "downloading logs: %v", err) } tarURL := fmt.Sprintf("https://storage.googleapis.com/%s/govim/%s/artifacts.tar.gz", *bucket, evalID) if err := download(tarURL); err != nil { fmt.Fprintf(os.Stderr, "downloading artifact tarball: %v", err) } } func download(artifactURL string) error { name := path.Base(artifactURL) resp, err := http.Get(artifactURL) if err != nil { return fmt.Errorf("fetching from GCS: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("got status code %d from GCS", resp.StatusCode) } data, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("reading result: %v", err) } if err := os.WriteFile(name, data, 0644); err != nil { return fmt.Errorf("writing artifact: %v", err) } return nil }
tools/gopls/integration/govim/artifacts.go/0
{ "file_path": "tools/gopls/integration/govim/artifacts.go", "repo_id": "tools", "token_count": 671 }
724
// 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 go1.20 // +build go1.20 package a var ( // Okay directive wise but the compiler will complain that // imports must appear before other declarations. //go:embed embedText // ok foo string ) import ( "fmt" _ "embed" ) // This is main function func main() { fmt.Println(s) }
tools/gopls/internal/analysis/embeddirective/testdata/src/a/import_present_go120.go/0
{ "file_path": "tools/gopls/internal/analysis/embeddirective/testdata/src/a/import_present_go120.go", "repo_id": "tools", "token_count": 146 }
725
// 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 fillswitch import altb "b" type typeA int const ( typeAOne typeA = iota typeATwo typeAThree ) func doSwitch() { var a typeA switch a { // want `Add cases for typeA` } switch a { // want `Add cases for typeA` case typeAOne: } switch a { case typeAOne: default: } switch a { case typeAOne: case typeATwo: case typeAThree: } var b altb.TypeB switch b { // want `Add cases for b.TypeB` case altb.TypeBOne: } } type notification interface { isNotification() } type notificationOne struct{} func (notificationOne) isNotification() {} type notificationTwo struct{} func (notificationTwo) isNotification() {} func doTypeSwitch() { var not notification switch not.(type) { // want `Add cases for notification` } switch not.(type) { // want `Add cases for notification` case notificationOne: } switch not.(type) { case notificationOne: case notificationTwo: } switch not.(type) { default: } var t data.ExportedInterface switch t { } }
tools/gopls/internal/analysis/fillswitch/testdata/src/a/a.go/0
{ "file_path": "tools/gopls/internal/analysis/fillswitch/testdata/src/a/a.go", "repo_id": "tools", "token_count": 397 }
726
package nonewvars func hello[T any]() int { var z T z := 1 // want "no new variables on left side of :=" }
tools/gopls/internal/analysis/nonewvars/testdata/src/typeparams/a.go/0
{ "file_path": "tools/gopls/internal/analysis/nonewvars/testdata/src/typeparams/a.go", "repo_id": "tools", "token_count": 41 }
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 simplifyrange import ( "bytes" _ "embed" "go/ast" "go/printer" "go/token" "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/analysisinternal" ) //go:embed doc.go var doc string var Analyzer = &analysis.Analyzer{ Name: "simplifyrange", Doc: analysisinternal.MustExtractDoc(doc, "simplifyrange"), Requires: []*analysis.Analyzer{inspect.Analyzer}, Run: run, URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/simplifyrange", } func run(pass *analysis.Pass) (interface{}, error) { inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) nodeFilter := []ast.Node{ (*ast.RangeStmt)(nil), } inspect.Preorder(nodeFilter, func(n ast.Node) { var copy *ast.RangeStmt // shallow-copy the AST before modifying { x := *n.(*ast.RangeStmt) copy = &x } end := newlineIndex(pass.Fset, copy) // Range statements of the form: for i, _ := range x {} var old ast.Expr if isBlank(copy.Value) { old = copy.Value copy.Value = nil } // Range statements of the form: for _ := range x {} if isBlank(copy.Key) && copy.Value == nil { old = copy.Key copy.Key = nil } // Return early if neither if condition is met. if old == nil { return } pass.Report(analysis.Diagnostic{ Pos: old.Pos(), End: old.End(), Message: "simplify range expression", SuggestedFixes: suggestedFixes(pass.Fset, copy, end), }) }) return nil, nil } func suggestedFixes(fset *token.FileSet, rng *ast.RangeStmt, end token.Pos) []analysis.SuggestedFix { var b bytes.Buffer printer.Fprint(&b, fset, rng) stmt := b.Bytes() index := bytes.Index(stmt, []byte("\n")) // If there is a new line character, then don't replace the body. if index != -1 { stmt = stmt[:index] } return []analysis.SuggestedFix{{ Message: "Remove empty value", TextEdits: []analysis.TextEdit{{ Pos: rng.Pos(), End: end, NewText: stmt[:index], }}, }} } func newlineIndex(fset *token.FileSet, rng *ast.RangeStmt) token.Pos { var b bytes.Buffer printer.Fprint(&b, fset, rng) contents := b.Bytes() index := bytes.Index(contents, []byte("\n")) if index == -1 { return rng.End() } return rng.Pos() + token.Pos(index) } func isBlank(x ast.Expr) bool { ident, ok := x.(*ast.Ident) return ok && ident.Name == "_" }
tools/gopls/internal/analysis/simplifyrange/simplifyrange.go/0
{ "file_path": "tools/gopls/internal/analysis/simplifyrange/simplifyrange.go", "repo_id": "tools", "token_count": 1077 }
728
// 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 stubmethods var _ I = Y{} // want "does not implement I" type I interface{ F() } type X struct{} func (X) F(string) {} type Y struct{ X }
tools/gopls/internal/analysis/stubmethods/testdata/src/typeparams/implement.go/0
{ "file_path": "tools/gopls/internal/analysis/stubmethods/testdata/src/typeparams/implement.go", "repo_id": "tools", "token_count": 99 }
729
// 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 a import ( "bytes" "fmt" "net/http" ) type parent interface { n(f bool) } type yuh struct { a int } func (y *yuh) n(f bool) { for i := 0; i < 10; i++ { fmt.Println(i) } } func a(i1 int, i2 int, i3 int) int { // want "unused parameter: i2" i3 += i1 _ = func(z int) int { // want "unused parameter: z" _ = 1 return 1 } return i3 } func b(c bytes.Buffer) { // want "unused parameter: c" _ = 1 } func z(h http.ResponseWriter, _ *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) } func mult(a, b int) int { // want "unused parameter: b" a += 1 return a } func y(a int) { panic("yo") } var _ = func(x int) {} // empty body: no diagnostic var _ = func(x int) { println() } // want "unused parameter: x" var ( calledGlobal = func(x int) { println() } // want "unused parameter: x" addressTakenGlobal = func(x int) { println() } // no report: function is address-taken ) func _() { calledGlobal(1) println(addressTakenGlobal) } func Exported(unused int) {} // no finding: an exported function may be address-taken type T int func (T) m(f bool) { println() } // want "unused parameter: f" func (T) n(f bool) { println() } // no finding: n may match the interface method parent.n func _() { var fib func(x, y int) int fib = func(x, y int) int { // want "unused parameter: y" if x < 2 { return x } return fib(x-1, 123) + fib(x-2, 456) } fib(10, 42) }
tools/gopls/internal/analysis/unusedparams/testdata/src/a/a.go/0
{ "file_path": "tools/gopls/internal/analysis/unusedparams/testdata/src/a/a.go", "repo_id": "tools", "token_count": 671 }
730
// 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 // This file defines gopls' driver for modular static analysis (go/analysis). import ( "bytes" "context" "crypto/sha256" "encoding/gob" "encoding/json" "errors" "fmt" "go/ast" "go/parser" "go/token" "go/types" "log" urlpkg "net/url" "path/filepath" "reflect" "runtime" "runtime/debug" "sort" "strings" "sync" "sync/atomic" "time" "golang.org/x/sync/errgroup" "golang.org/x/tools/go/analysis" "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/filecache" "golang.org/x/tools/gopls/internal/label" "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/astutil" "golang.org/x/tools/gopls/internal/util/bug" "golang.org/x/tools/gopls/internal/util/frob" "golang.org/x/tools/gopls/internal/util/maps" "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/facts" "golang.org/x/tools/internal/gcimporter" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/versions" ) /* DESIGN An analysis request (Snapshot.Analyze) is for a set of Analyzers and PackageIDs. The result is the set of diagnostics for those packages. Each request constructs a transitively closed DAG of nodes, each representing a package, then works bottom up in parallel postorder calling runCached to ensure that each node's analysis summary is up to date. The summary contains the analysis diagnostics as well as the intermediate results required by the recursion, such as serialized types and facts. The entire DAG is ephemeral. Each node in the DAG records the set of analyzers to run: the complete set for the root packages, and the "facty" subset for dependencies. Each package is thus analyzed at most once. The entire DAG shares a single FileSet for parsing and importing. Each node is processed by runCached. It gets the source file content hashes for package p, and the summaries of its "vertical" dependencies (direct imports), and from them it computes a key representing the unit of work (parsing, type-checking, and analysis) that it has to do. The key is a cryptographic hash of the "recipe" for this step, including the Metadata, the file contents, the set of analyzers, and the type and fact information from the vertical dependencies. The key is sought in a machine-global persistent file-system based cache. If this gopls process, or another gopls process on the same machine, has already performed this analysis step, runCached will make a cache hit and load the serialized summary of the results. If not, it will have to proceed to run() to parse and type-check the package and then apply a set of analyzers to it. (The set of analyzers applied to a single package itself forms a graph of "actions", and it too is evaluated in parallel postorder; these dependency edges within the same package are called "horizontal".) Finally it writes a new cache entry. The entry contains serialized types (export data) and analysis facts. Each node in the DAG acts like a go/types importer mapping, providing a consistent view of packages and their objects: the mapping for a node is a superset of its dependencies' mappings. Every node has an associated *types.Package, initially nil. A package is populated during run (cache miss) by type-checking its syntax; but for a cache hit, the package is populated lazily, i.e. not until it later becomes necessary because it is imported directly or referenced by export data higher up in the DAG. For types, we use "shallow" export data. Historically, the Go compiler always produced a summary of the types for a given package that included types from other packages that it indirectly referenced: "deep" export data. This had the advantage that the compiler (and analogous tools such as gopls) need only load one file per direct import. However, it meant that the files tended to get larger based on the level of the package in the import graph. For example, higher-level packages in the kubernetes module have over 1MB of "deep" export data, even when they have almost no content of their own, merely because they mention a major type that references many others. In pathological cases the export data was 300x larger than the source for a package due to this quadratic growth. "Shallow" export data means that the serialized types describe only a single package. If those types mention types from other packages, the type checker may need to request additional packages beyond just the direct imports. Type information for the entire transitive closure of imports is provided (lazily) by the DAG. For correct dependency analysis, the digest used as a cache key must reflect the "deep" export data, so it is derived recursively from the transitive closure. As an optimization, we needn't include every package of the transitive closure in the deep hash, only the packages that were actually requested by the type checker. This allows changes to a package that have no effect on its export data to be "pruned". The direct consumer will need to be re-executed, but if its export data is unchanged as a result, then indirect consumers may not need to be re-executed. This allows, for example, one to insert a print statement in a function and not "rebuild" the whole application (though export data does record line numbers and offsets of types which may be perturbed by otherwise insignificant changes.) The summary must record whether a package is transitively error-free (whether it would compile) because many analyzers are not safe to run on packages with inconsistent types. For fact encoding, we use the same fact set as the unitchecker (vet) to record and serialize analysis facts. The fact serialization mechanism is analogous to "deep" export data. */ // TODO(adonovan): // - Add a (white-box) test of pruning when a change doesn't affect export data. // - Optimise pruning based on subset of packages mentioned in exportdata. // - Better logging so that it is possible to deduce why an analyzer // is not being run--often due to very indirect failures. // Even if the ultimate consumer decides to ignore errors, // tests and other situations want to be assured of freedom from // errors, not just missing results. This should be recorded. // - Split this into a subpackage, gopls/internal/cache/driver, // consisting of this file and three helpers from errors.go. // The (*snapshot).Analyze method would stay behind and make calls // to the driver package. // Steps: // - define a narrow driver.Snapshot interface with only these methods: // Metadata(PackageID) Metadata // ReadFile(Context, URI) (file.Handle, error) // View() *View // for Options // - share cache.{goVersionRx,parseGoImpl} // AnalysisProgressTitle is the title of the progress report for ongoing // analysis. It is sought by regression tests for the progress reporting // feature. const AnalysisProgressTitle = "Analyzing Dependencies" // Analyze applies a set of analyzers to the package denoted by id, // and returns their diagnostics for that package. // // The analyzers list must be duplicate free; order does not matter. // // Notifications of progress may be sent to the optional reporter. func (s *Snapshot) Analyze(ctx context.Context, pkgs map[PackageID]*metadata.Package, analyzers []*settings.Analyzer, reporter *progress.Tracker) ([]*Diagnostic, error) { start := time.Now() // for progress reporting var tagStr string // sorted comma-separated list of PackageIDs { keys := make([]string, 0, len(pkgs)) for id := range pkgs { keys = append(keys, string(id)) } sort.Strings(keys) tagStr = strings.Join(keys, ",") } ctx, done := event.Start(ctx, "snapshot.Analyze", label.Package.Of(tagStr)) defer done() // Filter and sort enabled root analyzers. // A disabled analyzer may still be run if required by another. toSrc := make(map[*analysis.Analyzer]*settings.Analyzer) var enabledAnalyzers []*analysis.Analyzer // enabled subset + transitive requirements for _, a := range analyzers { if enabled, ok := s.Options().Analyses[a.Analyzer().Name]; enabled || !ok && a.EnabledByDefault() { toSrc[a.Analyzer()] = a enabledAnalyzers = append(enabledAnalyzers, a.Analyzer()) } } sort.Slice(enabledAnalyzers, func(i, j int) bool { return enabledAnalyzers[i].Name < enabledAnalyzers[j].Name }) analyzers = nil // prevent accidental use enabledAnalyzers = requiredAnalyzers(enabledAnalyzers) // Perform basic sanity checks. // (Ideally we would do this only once.) if err := analysis.Validate(enabledAnalyzers); err != nil { return nil, fmt.Errorf("invalid analyzer configuration: %v", err) } stableNames := make(map[*analysis.Analyzer]string) var facty []*analysis.Analyzer // facty subset of enabled + transitive requirements for _, a := range enabledAnalyzers { // TODO(adonovan): reject duplicate stable names (very unlikely). stableNames[a] = stableName(a) // Register fact types of all required analyzers. if len(a.FactTypes) > 0 { facty = append(facty, a) for _, f := range a.FactTypes { gob.Register(f) // <2us } } } facty = requiredAnalyzers(facty) // File set for this batch (entire graph) of analysis. fset := token.NewFileSet() // Starting from the root packages and following DepsByPkgPath, // build the DAG of packages we're going to analyze. // // Root nodes will run the enabled set of analyzers, // whereas dependencies will run only the facty set. // Because (by construction) enabled is a superset of facty, // we can analyze each node with exactly one set of analyzers. nodes := make(map[PackageID]*analysisNode) var leaves []*analysisNode // nodes with no unfinished successors var makeNode func(from *analysisNode, id PackageID) (*analysisNode, error) makeNode = func(from *analysisNode, id PackageID) (*analysisNode, error) { an, ok := nodes[id] if !ok { mp := s.Metadata(id) if mp == nil { return nil, bug.Errorf("no metadata for %s", id) } // -- preorder -- an = &analysisNode{ fset: fset, fsource: struct{ file.Source }{s}, // expose only ReadFile viewType: s.View().Type(), mp: mp, analyzers: facty, // all nodes run at least the facty analyzers allDeps: make(map[PackagePath]*analysisNode), exportDeps: make(map[PackagePath]*analysisNode), stableNames: stableNames, } nodes[id] = an // -- recursion -- // Build subgraphs for dependencies. an.succs = make(map[PackageID]*analysisNode, len(mp.DepsByPkgPath)) for _, depID := range mp.DepsByPkgPath { dep, err := makeNode(an, depID) if err != nil { return nil, err } an.succs[depID] = dep // Compute the union of all dependencies. // (This step has quadratic complexity.) for pkgPath, node := range dep.allDeps { an.allDeps[pkgPath] = node } } // -- postorder -- an.allDeps[mp.PkgPath] = an // add self entry (reflexive transitive closure) // Add leaf nodes (no successors) directly to queue. if len(an.succs) == 0 { leaves = append(leaves, an) } // Load the contents of each compiled Go file through // the snapshot's cache. (These are all cache hits as // files are pre-loaded following packages.Load) an.files = make([]file.Handle, len(mp.CompiledGoFiles)) for i, uri := range mp.CompiledGoFiles { fh, err := s.ReadFile(ctx, uri) if err != nil { return nil, err } an.files[i] = fh } } // Add edge from predecessor. if from != nil { from.unfinishedSuccs.Add(+1) // incref an.preds = append(an.preds, from) } an.unfinishedPreds.Add(+1) return an, nil } // For root packages, we run the enabled set of analyzers. var roots []*analysisNode for id := range pkgs { root, err := makeNode(nil, id) if err != nil { return nil, err } root.analyzers = enabledAnalyzers roots = append(roots, root) } // Now that we have read all files, // we no longer need the snapshot. // (but options are needed for progress reporting) options := s.Options() s = nil // Progress reporting. If supported, gopls reports progress on analysis // passes that are taking a long time. maybeReport := func(completed int64) {} // Enable progress reporting if enabled by the user // and we have a capable reporter. if reporter != nil && reporter.SupportsWorkDoneProgress() && options.AnalysisProgressReporting { var reportAfter = options.ReportAnalysisProgressAfter // tests may set this to 0 const reportEvery = 1 * time.Second ctx, cancel := context.WithCancel(ctx) defer cancel() var ( reportMu sync.Mutex lastReport time.Time wd *progress.WorkDone ) defer func() { reportMu.Lock() defer reportMu.Unlock() if wd != nil { wd.End(ctx, "Done.") // ensure that the progress report exits } }() maybeReport = func(completed int64) { now := time.Now() if now.Sub(start) < reportAfter { return } reportMu.Lock() defer reportMu.Unlock() if wd == nil { wd = reporter.Start(ctx, AnalysisProgressTitle, "", nil, cancel) } if now.Sub(lastReport) > reportEvery { lastReport = now // Trailing space is intentional: some LSP clients strip newlines. msg := fmt.Sprintf(`Indexed %d/%d packages. (Set "analysisProgressReporting" to false to disable notifications.)`, completed, len(nodes)) pct := 100 * float64(completed) / float64(len(nodes)) wd.Report(ctx, msg, pct) } } } // Execute phase: run leaves first, adding // new nodes to the queue as they become leaves. var g errgroup.Group // Analysis is CPU-bound. // // Note: avoid g.SetLimit here: it makes g.Go stop accepting work, which // prevents workers from enqeuing, and thus finishing, and thus allowing the // group to make progress: deadlock. limiter := make(chan unit, runtime.GOMAXPROCS(0)) var completed atomic.Int64 var enqueue func(*analysisNode) enqueue = func(an *analysisNode) { g.Go(func() error { limiter <- unit{} defer func() { <-limiter }() summary, err := an.runCached(ctx) if err != nil { return err // cancelled, or failed to produce a package } maybeReport(completed.Add(1)) an.summary = summary // Notify each waiting predecessor, // and enqueue it when it becomes a leaf. for _, pred := range an.preds { if pred.unfinishedSuccs.Add(-1) == 0 { // decref enqueue(pred) } } // Notify each successor that we no longer need // its action summaries, which hold Result values. // After the last one, delete it, so that we // free up large results such as SSA. for _, succ := range an.succs { succ.decrefPreds() } return nil }) } for _, leaf := range leaves { enqueue(leaf) } if err := g.Wait(); err != nil { return nil, err // cancelled, or failed to produce a package } // Inv: all root nodes now have a summary (#66732). // // We know this is falsified empirically. This means either // the summary was "successfully" set to nil (above), or there // is a problem with the graph such the enqueuing leaves does // not lead to completion of roots (or an error). for _, root := range roots { if root.summary == nil { bug.Report("root analysisNode has nil summary") } } // Report diagnostics only from enabled actions that succeeded. // Errors from creating or analyzing packages are ignored. // Diagnostics are reported in the order of the analyzers argument. // // TODO(adonovan): ignoring action errors gives the caller no way // to distinguish "there are no problems in this code" from // "the code (or analyzers!) are so broken that we couldn't even // begin the analysis you asked for". // Even if current callers choose to discard the // results, we should propagate the per-action errors. var results []*Diagnostic for _, root := range roots { for _, a := range enabledAnalyzers { // Skip analyzers that were added only to // fulfil requirements of the original set. srcAnalyzer, ok := toSrc[a] if !ok { // Although this 'skip' operation is logically sound, // it is nonetheless surprising that its absence should // cause #60909 since none of the analyzers currently added for // requirements (e.g. ctrlflow, inspect, buildssa) // is capable of reporting diagnostics. if summary := root.summary.Actions[stableNames[a]]; summary != nil { if n := len(summary.Diagnostics); n > 0 { bug.Reportf("Internal error: got %d unexpected diagnostics from analyzer %s. This analyzer was added only to fulfil the requirements of the requested set of analyzers, and it is not expected that such analyzers report diagnostics. Please report this in issue #60909.", n, a) } } continue } // Inv: root.summary is the successful result of run (via runCached). // TODO(adonovan): fix: root.summary is sometimes nil! (#66732). summary, ok := root.summary.Actions[stableNames[a]] if summary == nil { panic(fmt.Sprintf("analyzeSummary.Actions[%q] = (nil, %t); got %v (#60551)", stableNames[a], ok, root.summary.Actions)) } if summary.Err != "" { continue // action failed } for _, gobDiag := range summary.Diagnostics { results = append(results, toSourceDiagnostic(srcAnalyzer, &gobDiag)) } } } return results, nil } func (an *analysisNode) decrefPreds() { if an.unfinishedPreds.Add(-1) == 0 { an.summary.Actions = nil } } // An analysisNode is a node in a doubly-linked DAG isomorphic to the // import graph. Each node represents a single package, and the DAG // represents a batch of analysis work done at once using a single // realm of token.Pos or types.Object values. // // A complete DAG is created anew for each batch of analysis; // subgraphs are not reused over time. Each node's *types.Package // field is initially nil and is populated on demand, either from // type-checking syntax trees (typeCheck) or from importing export // data (_import). When this occurs, the typesOnce event becomes // "done". // // Each node's allDeps map is a "view" of all its dependencies keyed by // package path, which defines the types.Importer mapping used when // populating the node's types.Package. Different nodes have different // views (e.g. due to variants), but two nodes that are related by // graph ordering have views that are consistent in their overlap. // exportDeps is the subset actually referenced by export data; // this is the set for which we attempt to decode facts. // // Each node's run method is called in parallel postorder. On success, // its summary field is populated, either from the cache (hit), or by // type-checking and analyzing syntax (miss). type analysisNode struct { fset *token.FileSet // file set shared by entire batch (DAG) fsource file.Source // Snapshot.ReadFile, for use by Pass.ReadFile viewType ViewType // type of view mp *metadata.Package // metadata for this package files []file.Handle // contents of CompiledGoFiles analyzers []*analysis.Analyzer // set of analyzers to run preds []*analysisNode // graph edges: succs map[PackageID]*analysisNode // (preds -> self -> succs) unfinishedSuccs atomic.Int32 unfinishedPreds atomic.Int32 // effectively a summary.Actions refcount allDeps map[PackagePath]*analysisNode // all dependencies including self exportDeps map[PackagePath]*analysisNode // subset of allDeps ref'd by export data (+self) summary *analyzeSummary // serializable result of analyzing this package stableNames map[*analysis.Analyzer]string // cross-process stable names for Analyzers typesOnce sync.Once // guards lazy population of types and typesErr fields types *types.Package // type information lazily imported from summary typesErr error // an error producing type information } func (an *analysisNode) String() string { return string(an.mp.ID) } // _import imports this node's types.Package from export data, if not already done. // Precondition: analysis was a success. // Postcondition: an.types and an.exportDeps are populated. func (an *analysisNode) _import() (*types.Package, error) { an.typesOnce.Do(func() { if an.mp.PkgPath == "unsafe" { an.types = types.Unsafe return } an.types = types.NewPackage(string(an.mp.PkgPath), string(an.mp.Name)) // getPackages recursively imports each dependency // referenced by the export data, in parallel. getPackages := func(items []gcimporter.GetPackagesItem) error { var g errgroup.Group for i, item := range items { path := PackagePath(item.Path) dep, ok := an.allDeps[path] if !ok { // This early return bypasses Wait; that's ok. return fmt.Errorf("%s: unknown dependency %q", an.mp, path) } an.exportDeps[path] = dep // record, for later fact decoding if dep == an { if an.typesErr != nil { return an.typesErr } else { items[i].Pkg = an.types } } else { i := i g.Go(func() error { depPkg, err := dep._import() if err == nil { items[i].Pkg = depPkg } return err }) } } return g.Wait() } pkg, err := gcimporter.IImportShallow(an.fset, getPackages, an.summary.Export, string(an.mp.PkgPath), bug.Reportf) if err != nil { an.typesErr = bug.Errorf("%s: invalid export data: %v", an.mp, err) an.types = nil } else if pkg != an.types { log.Fatalf("%s: inconsistent packages", an.mp) } }) return an.types, an.typesErr } // analyzeSummary is a gob-serializable summary of successfully // applying a list of analyzers to a package. type analyzeSummary struct { Export []byte // encoded types of package DeepExportHash file.Hash // hash of reflexive transitive closure of export data Compiles bool // transitively free of list/parse/type errors Actions actionMap // maps analyzer stablename to analysis results (*actionSummary) } // actionMap defines a stable Gob encoding for a map. // TODO(adonovan): generalize and move to a library when we can use generics. type actionMap map[string]*actionSummary var ( _ gob.GobEncoder = (actionMap)(nil) _ gob.GobDecoder = (*actionMap)(nil) ) type actionsMapEntry struct { K string V *actionSummary } func (m actionMap) GobEncode() ([]byte, error) { entries := make([]actionsMapEntry, 0, len(m)) for k, v := range m { entries = append(entries, actionsMapEntry{k, v}) } sort.Slice(entries, func(i, j int) bool { return entries[i].K < entries[j].K }) var buf bytes.Buffer err := gob.NewEncoder(&buf).Encode(entries) return buf.Bytes(), err } func (m *actionMap) GobDecode(data []byte) error { var entries []actionsMapEntry if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&entries); err != nil { return err } *m = make(actionMap, len(entries)) for _, e := range entries { (*m)[e.K] = e.V } return nil } // actionSummary is a gob-serializable summary of one possibly failed analysis action. // If Err is non-empty, the other fields are undefined. type actionSummary struct { Facts []byte // the encoded facts.Set FactsHash file.Hash // hash(Facts) Diagnostics []gobDiagnostic Err string // "" => success } // runCached applies a list of analyzers (plus any others // transitively required by them) to a package. It succeeds as long // as it could produce a types.Package, even if there were direct or // indirect list/parse/type errors, and even if all the analysis // actions failed. It usually fails only if the package was unknown, // a file was missing, or the operation was cancelled. // // Postcondition: runCached must not continue to use the snapshot // (in background goroutines) after it has returned; see memoize.RefCounted. func (an *analysisNode) runCached(ctx context.Context) (*analyzeSummary, error) { // At this point we have the action results (serialized // packages and facts) of our immediate dependencies, // and the metadata and content of this package. // // We now compute a hash for all our inputs, and consult a // global cache of promised results. If nothing material // has changed, we'll make a hit in the shared cache. // // The hash of our inputs is based on the serialized export // data and facts so that immaterial changes can be pruned // without decoding. key := an.cacheKey() // Access the cache. var summary *analyzeSummary const cacheKind = "analysis" if data, err := filecache.Get(cacheKind, key); err == nil { // cache hit analyzeSummaryCodec.Decode(data, &summary) if summary == nil { // debugging #66732 bug.Reportf("analyzeSummaryCodec.Decode yielded nil *analyzeSummary") } } else if err != filecache.ErrNotFound { return nil, bug.Errorf("internal error reading shared cache: %v", err) } else { // Cache miss: do the work. var err error summary, err = an.run(ctx) if err != nil { return nil, err } if summary == nil { // debugging #66732 (can't happen) bug.Reportf("analyzeNode.run returned nil *analyzeSummary") } an.unfinishedPreds.Add(+1) // incref go func() { defer an.decrefPreds() //decref cacheLimit <- unit{} // acquire token defer func() { <-cacheLimit }() // release token data := analyzeSummaryCodec.Encode(summary) if false { log.Printf("Set key=%d value=%d id=%s\n", len(key), len(data), an.mp.ID) } if err := filecache.Set(cacheKind, key, data); err != nil { event.Error(ctx, "internal error updating analysis shared cache", err) } }() } return summary, nil } // cacheLimit reduces parallelism of cache updates. // We allow more than typical GOMAXPROCS as it's a mix of CPU and I/O. var cacheLimit = make(chan unit, 32) // analysisCacheKey returns a cache key that is a cryptographic digest // of the all the values that might affect type checking and analysis: // the analyzer names, package metadata, names and contents of // compiled Go files, and vdeps (successor) information // (export data and facts). func (an *analysisNode) cacheKey() [sha256.Size]byte { 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. // analyzers fmt.Fprintf(hasher, "analyzers: %d\n", len(an.analyzers)) for _, a := range an.analyzers { fmt.Fprintln(hasher, a.Name) } // package metadata mp := an.mp fmt.Fprintf(hasher, "package: %s %s %s\n", mp.ID, mp.Name, mp.PkgPath) fmt.Fprintf(hasher, "viewtype: %s\n", an.viewType) // (affects diagnostics) // We can ignore m.DepsBy{Pkg,Import}Path: although the logic // uses those fields, we account for them by hashing vdeps. // type sizes wordSize := an.mp.TypesSizes.Sizeof(types.Typ[types.Int]) maxAlign := an.mp.TypesSizes.Alignof(types.NewPointer(types.Typ[types.Int64])) fmt.Fprintf(hasher, "sizes: %d %d\n", wordSize, maxAlign) // metadata errors: used for 'compiles' field fmt.Fprintf(hasher, "errors: %d", len(mp.Errors)) // module Go version if mp.Module != nil && mp.Module.GoVersion != "" { fmt.Fprintf(hasher, "go %s\n", mp.Module.GoVersion) } // file names and contents fmt.Fprintf(hasher, "files: %d\n", len(an.files)) for _, fh := range an.files { fmt.Fprintln(hasher, fh.Identity()) } // vdeps, in PackageID order depIDs := maps.Keys(an.succs) // TODO(adonovan): use go1.2x slices.Sort(depIDs). sort.Slice(depIDs, func(i, j int) bool { return depIDs[i] < depIDs[j] }) for _, depID := range depIDs { vdep := an.succs[depID] fmt.Fprintf(hasher, "dep: %s\n", vdep.mp.PkgPath) fmt.Fprintf(hasher, "export: %s\n", vdep.summary.DeepExportHash) // action results: errors and facts actions := vdep.summary.Actions names := make([]string, 0, len(actions)) for name := range actions { names = append(names, name) } sort.Strings(names) for _, name := range names { summary := actions[name] fmt.Fprintf(hasher, "action %s\n", name) if summary.Err != "" { fmt.Fprintf(hasher, "error %s\n", summary.Err) } else { fmt.Fprintf(hasher, "facts %s\n", summary.FactsHash) // We can safely omit summary.diagnostics // from the key since they have no downstream effect. } } } var hash [sha256.Size]byte hasher.Sum(hash[:0]) return hash } // run implements the cache-miss case. // This function does not access the snapshot. // // Postcondition: on success, the analyzeSummary.Actions // key set is {a.Name for a in analyzers}. func (an *analysisNode) run(ctx context.Context) (*analyzeSummary, error) { // Parse only the "compiled" Go files. // Do the computation in parallel. parsed := make([]*parsego.File, len(an.files)) { var group errgroup.Group group.SetLimit(4) // not too much: run itself is already called in parallel for i, fh := range an.files { i, fh := i, fh group.Go(func() error { // Call parseGoImpl directly, not the caching wrapper, // as cached ASTs require the global FileSet. // ast.Object resolution is unfortunately an implied part of the // go/analysis contract. pgf, err := parseGoImpl(ctx, an.fset, fh, parsego.Full&^parser.SkipObjectResolution, false) parsed[i] = pgf return err }) } if err := group.Wait(); err != nil { return nil, err // cancelled, or catastrophic error (e.g. missing file) } } // Type-check the package syntax. pkg := an.typeCheck(parsed) // Publish the completed package. an.typesOnce.Do(func() { an.types = pkg.types }) if an.types != pkg.types { log.Fatalf("typesOnce prematurely done") } // Compute the union of exportDeps across our direct imports. // This is the set that will be needed by the fact decoder. allExportDeps := make(map[PackagePath]*analysisNode) for _, succ := range an.succs { for k, v := range succ.exportDeps { allExportDeps[k] = v } } // The fact decoder needs a means to look up a Package by path. pkg.factsDecoder = facts.NewDecoderFunc(pkg.types, func(path string) *types.Package { // Note: Decode is called concurrently, and thus so is this function. // Does the fact relate to a package referenced by export data? if dep, ok := allExportDeps[PackagePath(path)]; ok { dep.typesOnce.Do(func() { log.Fatal("dep.types not populated") }) if dep.typesErr == nil { return dep.types } return nil } // If the fact relates to a dependency not referenced // by export data, it is safe to ignore it. // (In that case dep.types exists but may be unpopulated // or in the process of being populated from export data.) if an.allDeps[PackagePath(path)] == nil { log.Fatalf("fact package %q is not a dependency", path) } return nil }) // Poll cancellation state. if err := ctx.Err(); err != nil { return nil, err } // -- analysis -- // Build action graph for this package. // Each graph node (action) is one unit of analysis. actions := make(map[*analysis.Analyzer]*action) var mkAction func(a *analysis.Analyzer) *action mkAction = func(a *analysis.Analyzer) *action { act, ok := actions[a] if !ok { var hdeps []*action for _, req := range a.Requires { hdeps = append(hdeps, mkAction(req)) } act = &action{ a: a, fsource: an.fsource, stableName: an.stableNames[a], pkg: pkg, vdeps: an.succs, hdeps: hdeps, } actions[a] = act } return act } // Build actions for initial package. var roots []*action for _, a := range an.analyzers { roots = append(roots, mkAction(a)) } // Execute the graph in parallel. execActions(ctx, roots) // Inv: each root's summary is set (whether success or error). // Don't return (or cache) the result in case of cancellation. if err := ctx.Err(); err != nil { return nil, err // cancelled } // Return summaries only for the requested actions. summaries := make(map[string]*actionSummary) for _, root := range roots { if root.summary == nil { panic("root has nil action.summary (#60551)") } summaries[root.stableName] = root.summary } return &analyzeSummary{ Export: pkg.export, DeepExportHash: pkg.deepExportHash, Compiles: pkg.compiles, Actions: summaries, }, nil } // Postcondition: analysisPackage.types and an.exportDeps are populated. func (an *analysisNode) typeCheck(parsed []*parsego.File) *analysisPackage { mp := an.mp if false { // debugging log.Println("typeCheck", mp.ID) } pkg := &analysisPackage{ mp: mp, fset: an.fset, parsed: parsed, files: make([]*ast.File, len(parsed)), compiles: len(mp.Errors) == 0, // false => list error types: types.NewPackage(string(mp.PkgPath), string(mp.Name)), typesInfo: &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Instances: make(map[*ast.Ident]types.Instance), Implicits: make(map[ast.Node]types.Object), Selections: make(map[*ast.SelectorExpr]*types.Selection), Scopes: make(map[ast.Node]*types.Scope), Uses: make(map[*ast.Ident]types.Object), }, typesSizes: mp.TypesSizes, } versions.InitFileVersions(pkg.typesInfo) // Unsafe has no syntax. if mp.PkgPath == "unsafe" { pkg.types = types.Unsafe return pkg } for i, p := range parsed { pkg.files[i] = p.File if p.ParseErr != nil { pkg.compiles = false // parse error } } for _, vdep := range an.succs { if !vdep.summary.Compiles { pkg.compiles = false // transitive error } } cfg := &types.Config{ Sizes: mp.TypesSizes, Error: func(e error) { pkg.compiles = false // type error // Suppress type errors in files with parse errors // as parser recovery can be quite lossy (#59888). typeError := e.(types.Error) for _, p := range parsed { if p.ParseErr != nil && astutil.NodeContains(p.File, typeError.Pos) { return } } pkg.typeErrors = append(pkg.typeErrors, typeError) }, Importer: importerFunc(func(importPath string) (*types.Package, error) { // Beware that returning an error from this function // will cause the type checker to synthesize a fake // package whose Path is importPath, potentially // losing a vendor/ prefix. If type-checking errors // are swallowed, these packages may be confusing. // Map ImportPath to ID. id, ok := mp.DepsByImpPath[ImportPath(importPath)] if !ok { // The import syntax is inconsistent with the metadata. // This could be because the import declaration was // incomplete and the metadata only includes complete // imports; or because the metadata ignores import // edges that would lead to cycles in the graph. return nil, fmt.Errorf("missing metadata for import of %q", importPath) } // Map ID to node. (id may be "") dep := an.succs[id] if dep == nil { // Analogous to (*snapshot).missingPkgError // in the logic for regular type-checking, // but without a snapshot we can't provide // such detail, and anyway most analysis // failures aren't surfaced in the UI. return nil, fmt.Errorf("no required module provides analysis package %q (id=%q)", importPath, id) } // (Duplicates logic from check.go.) if !metadata.IsValidImport(an.mp.PkgPath, dep.mp.PkgPath, an.viewType != GoPackagesDriverView) { return nil, fmt.Errorf("invalid use of internal package %s", importPath) } return dep._import() }), } // Set Go dialect. if mp.Module != nil && mp.Module.GoVersion != "" { goVersion := "go" + mp.Module.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. // TODO(adonovan): do we actually need this?? typesinternal.SetUsesCgo(cfg) check := types.NewChecker(cfg, pkg.fset, pkg.types, pkg.typesInfo) // Type checking errors are handled via the config, so ignore them here. _ = check.Files(pkg.files) // debugging (type errors are quite normal) if false { if pkg.typeErrors != nil { log.Printf("package %s has type errors: %v", pkg.types.Path(), pkg.typeErrors) } } // Emit the export data and compute the recursive hash. export, err := gcimporter.IExportShallow(pkg.fset, pkg.types, bug.Reportf) if err != nil { // TODO(adonovan): in light of exporter bugs such as #57729, // consider using bug.Report here and retrying the IExportShallow // call here using an empty types.Package. log.Fatalf("internal error writing shallow export data: %v", err) } pkg.export = export // Compute a recursive hash to account for the export data of // this package and each dependency referenced by it. // Also, populate exportDeps. hash := sha256.New() fmt.Fprintf(hash, "%s %d\n", mp.PkgPath, len(export)) hash.Write(export) paths, err := readShallowManifest(export) if err != nil { log.Fatalf("internal error: bad export data: %v", err) } for _, path := range paths { dep, ok := an.allDeps[path] if !ok { log.Fatalf("%s: missing dependency: %q", an, path) } fmt.Fprintf(hash, "%s %s\n", dep.mp.PkgPath, dep.summary.DeepExportHash) an.exportDeps[path] = dep } an.exportDeps[mp.PkgPath] = an // self hash.Sum(pkg.deepExportHash[:0]) return pkg } // readShallowManifest returns the manifest of packages referenced by // a shallow export data file for a package (excluding the package itself). // TODO(adonovan): add a test. func readShallowManifest(export []byte) ([]PackagePath, error) { const selfPath = "<self>" // dummy path var paths []PackagePath getPackages := func(items []gcimporter.GetPackagesItem) error { paths = []PackagePath{} // non-nil for _, item := range items { if item.Path != selfPath { paths = append(paths, PackagePath(item.Path)) } } return errors.New("stop") // terminate importer } _, err := gcimporter.IImportShallow(token.NewFileSet(), getPackages, export, selfPath, bug.Reportf) if paths == nil { if err != nil { return nil, err // failed before getPackages callback } return nil, bug.Errorf("internal error: IImportShallow did not call getPackages") } return paths, nil // success } // analysisPackage contains information about a package, including // syntax trees, used transiently during its type-checking and analysis. type analysisPackage struct { mp *metadata.Package fset *token.FileSet // local to this package parsed []*parsego.File files []*ast.File // same as parsed[i].File types *types.Package compiles bool // package is transitively free of list/parse/type errors factsDecoder *facts.Decoder export []byte // encoding of types.Package deepExportHash file.Hash // reflexive transitive hash of export data typesInfo *types.Info typeErrors []types.Error typesSizes types.Sizes } // An action represents one unit of analysis work: the application of // one analysis to one package. Actions form a DAG, both within a // package (as different analyzers are applied, either in sequence or // parallel), and across packages (as dependencies are analyzed). type action struct { once sync.Once a *analysis.Analyzer fsource file.Source // Snapshot.ReadFile, for Pass.ReadFile stableName string // cross-process stable name of analyzer pkg *analysisPackage hdeps []*action // horizontal dependencies vdeps map[PackageID]*analysisNode // vertical dependencies // results of action.exec(): result interface{} // result of Run function, of type a.ResultType summary *actionSummary err error } func (act *action) String() string { return fmt.Sprintf("%s@%s", act.a.Name, act.pkg.mp.ID) } // execActions executes a set of action graph nodes in parallel. // Postcondition: each action.summary is set, even in case of error. func execActions(ctx context.Context, actions []*action) { var wg sync.WaitGroup for _, act := range actions { act := act wg.Add(1) go func() { defer wg.Done() act.once.Do(func() { execActions(ctx, act.hdeps) // analyze "horizontal" dependencies act.result, act.summary, act.err = act.exec(ctx) if act.err != nil { act.summary = &actionSummary{Err: act.err.Error()} // TODO(adonovan): suppress logging. But // shouldn't the root error's causal chain // include this information? if false { // debugging log.Printf("act.exec(%v) failed: %v", act, act.err) } } }) if act.summary == nil { panic("nil action.summary (#60551)") } }() } wg.Wait() } // exec defines the execution of a single action. // It returns the (ephemeral) result of the analyzer's Run function, // along with its (serializable) facts and diagnostics. // Or it returns an error if the analyzer did not run to // completion and deliver a valid result. func (act *action) exec(ctx context.Context) (any, *actionSummary, error) { analyzer := act.a pkg := act.pkg hasFacts := len(analyzer.FactTypes) > 0 // Report an error if any action dependency (vertical or horizontal) failed. // To avoid long error messages describing chains of failure, // we return the dependencies' error' unadorned. if hasFacts { // TODO(adonovan): use deterministic order. for _, vdep := range act.vdeps { if summ := vdep.summary.Actions[act.stableName]; summ.Err != "" { return nil, nil, errors.New(summ.Err) } } } for _, dep := range act.hdeps { if dep.err != nil { return nil, nil, dep.err } } // Inv: all action dependencies succeeded. // Were there list/parse/type errors that might prevent analysis? if !pkg.compiles && !analyzer.RunDespiteErrors { return nil, nil, fmt.Errorf("skipping analysis %q because package %q does not compile", analyzer.Name, pkg.mp.ID) } // Inv: package is well-formed enough to proceed with analysis. if false { // debugging log.Println("action.exec", act) } // Gather analysis Result values from horizontal dependencies. inputs := make(map[*analysis.Analyzer]interface{}) for _, dep := range act.hdeps { inputs[dep.a] = dep.result } // TODO(adonovan): opt: facts.Set works but it may be more // efficient to fork and tailor it to our precise needs. // // We've already sharded the fact encoding by action // so that it can be done in parallel. // We could eliminate locking. // We could also dovetail more closely with the export data // decoder to obtain a more compact representation of // packages and objects (e.g. its internal IDs, instead // of PkgPaths and objectpaths.) // More importantly, we should avoid re-export of // facts that related to objects that are discarded // by "deep" export data. Better still, use a "shallow" approach. // Read and decode analysis facts for each direct import. factset, err := pkg.factsDecoder.Decode(func(pkgPath string) ([]byte, error) { if !hasFacts { return nil, nil // analyzer doesn't use facts, so no vdeps } // Package.Imports() may contain a fake "C" package. Ignore it. if pkgPath == "C" { return nil, nil } id, ok := pkg.mp.DepsByPkgPath[PackagePath(pkgPath)] if !ok { // This may mean imp was synthesized by the type // checker because it failed to import it for any reason // (e.g. bug processing export data; metadata ignoring // a cycle-forming import). // In that case, the fake package's imp.Path // is set to the failed importPath (and thus // it may lack a "vendor/" prefix). // // For now, silently ignore it on the assumption // that the error is already reported elsewhere. // return nil, fmt.Errorf("missing metadata") return nil, nil } vdep := act.vdeps[id] if vdep == nil { return nil, bug.Errorf("internal error in %s: missing vdep for id=%s", pkg.types.Path(), id) } return vdep.summary.Actions[act.stableName].Facts, nil }) if err != nil { return nil, nil, fmt.Errorf("internal error decoding analysis facts: %w", err) } // TODO(adonovan): make Export*Fact panic rather than discarding // undeclared fact types, so that we discover bugs in analyzers. factFilter := make(map[reflect.Type]bool) for _, f := range analyzer.FactTypes { factFilter[reflect.TypeOf(f)] = true } // posToLocation converts from token.Pos to protocol form. posToLocation := func(start, end token.Pos) (protocol.Location, error) { tokFile := pkg.fset.File(start) // Find existing mapper by file name. // (Don't require an exact token.File match // as the analyzer may have re-parsed the file.) var ( mapper *protocol.Mapper fixed bool ) for _, p := range pkg.parsed { if p.Tok.Name() == tokFile.Name() { mapper = p.Mapper fixed = p.Fixed() // suppress some assertions after parser recovery break } } if mapper == nil { // The start position was not among the package's parsed // Go files, indicating that the analyzer added new files // to the FileSet. // // For example, the cgocall analyzer re-parses and // type-checks some of the files in a special environment; // and asmdecl and other low-level runtime analyzers call // ReadFile to parse non-Go files. // (This is a supported feature, documented at go/analysis.) // // In principle these files could be: // // - OtherFiles (non-Go files such as asm). // However, we set Pass.OtherFiles=[] because // gopls won't service "diagnose" requests // for non-Go files, so there's no point // reporting diagnostics in them. // // - IgnoredFiles (files tagged for other configs). // However, we set Pass.IgnoredFiles=[] because, // in most cases, zero-config gopls should create // another view that covers these files. // // - Referents of //line directives, as in cgo packages. // The file names in this case are not known a priori. // gopls generally tries to avoid honoring line directives, // but analyzers such as cgocall may honor them. // // In short, it's unclear how this can be reached // other than due to an analyzer bug. return protocol.Location{}, bug.Errorf("diagnostic location is not among files of package: %s", tokFile.Name()) } // Inv: mapper != nil if end == token.NoPos { end = start } // debugging #64547 fileStart := token.Pos(tokFile.Base()) fileEnd := fileStart + token.Pos(tokFile.Size()) if start < fileStart { if !fixed { bug.Reportf("start < start of file") } start = fileStart } if end < start { // This can happen if End is zero (#66683) // or a small positive displacement from zero // due to recursive Node.End() computation. // This usually arises from poor parser recovery // of an incomplete term at EOF. if !fixed { bug.Reportf("end < start of file") } end = fileEnd } if end > fileEnd+1 { if !fixed { bug.Reportf("end > end of file + 1") } end = fileEnd } return mapper.PosLocation(tokFile, start, end) } // Now run the (pkg, analyzer) action. var diagnostics []gobDiagnostic pass := &analysis.Pass{ Analyzer: analyzer, Fset: pkg.fset, Files: pkg.files, OtherFiles: nil, // since gopls doesn't handle non-Go (e.g. asm) files IgnoredFiles: nil, // zero-config gopls should analyze these files in another view Pkg: pkg.types, TypesInfo: pkg.typesInfo, TypesSizes: pkg.typesSizes, TypeErrors: pkg.typeErrors, ResultOf: inputs, Report: func(d analysis.Diagnostic) { diagnostic, err := toGobDiagnostic(posToLocation, analyzer, d) if err != nil { // Don't bug.Report here: these errors all originate in // posToLocation, and we can more accurately discriminate // severe errors from benign ones in that function. event.Error(ctx, fmt.Sprintf("internal error converting diagnostic from analyzer %q", analyzer.Name), err) return } diagnostics = append(diagnostics, diagnostic) }, ImportObjectFact: factset.ImportObjectFact, ExportObjectFact: factset.ExportObjectFact, ImportPackageFact: factset.ImportPackageFact, ExportPackageFact: factset.ExportPackageFact, AllObjectFacts: func() []analysis.ObjectFact { return factset.AllObjectFacts(factFilter) }, AllPackageFacts: func() []analysis.PackageFact { return factset.AllPackageFacts(factFilter) }, } pass.ReadFile = func(filename string) ([]byte, error) { // Read file from snapshot, to ensure reads are consistent. // // TODO(adonovan): make the dependency analysis sound by // incorporating these additional files into the the analysis // hash. This requires either (a) preemptively reading and // hashing a potentially large number of mostly irrelevant // files; or (b) some kind of dynamic dependency discovery // system like used in Bazel for C++ headers. Neither entices. if err := analysisinternal.CheckReadable(pass, filename); err != nil { return nil, err } h, err := act.fsource.ReadFile(ctx, protocol.URIFromPath(filename)) if err != nil { return nil, err } content, err := h.Content() if err != nil { return nil, err // file doesn't exist } return slices.Clone(content), nil // follow ownership of os.ReadFile } // Recover from panics (only) within the analyzer logic. // (Use an anonymous function to limit the recover scope.) var result interface{} func() { start := time.Now() defer func() { if r := recover(); r != nil { // An Analyzer panicked, likely due to a bug. // // In general we want to discover and fix such panics quickly, // so we don't suppress them, but some bugs in third-party // analyzers cannot be quickly fixed, so we use an allowlist // to suppress panics. const strict = true if strict && bug.PanicOnBugs && analyzer.Name != "buildir" { // see https://github.com/dominikh/go-tools/issues/1343 // Uncomment this when debugging suspected failures // in the driver, not the analyzer. if false { debug.SetTraceback("all") // show all goroutines } panic(r) } else { // In production, suppress the panic and press on. err = fmt.Errorf("analysis %s for package %s panicked: %v", analyzer.Name, pass.Pkg.Path(), r) } } // Accumulate running time for each checker. analyzerRunTimesMu.Lock() analyzerRunTimes[analyzer] += time.Since(start) analyzerRunTimesMu.Unlock() }() result, err = pass.Analyzer.Run(pass) }() if err != nil { return nil, nil, err } if got, want := reflect.TypeOf(result), pass.Analyzer.ResultType; got != want { return nil, nil, bug.Errorf( "internal error: on package %s, analyzer %s returned a result of type %v, but declared ResultType %v", pass.Pkg.Path(), pass.Analyzer, got, want) } // Disallow Export*Fact calls after Run. // (A panic means the Analyzer is abusing concurrency.) pass.ExportObjectFact = func(obj types.Object, fact analysis.Fact) { panic(fmt.Sprintf("%v: Pass.ExportObjectFact(%s, %T) called after Run", act, obj, fact)) } pass.ExportPackageFact = func(fact analysis.Fact) { panic(fmt.Sprintf("%v: Pass.ExportPackageFact(%T) called after Run", act, fact)) } factsdata := factset.Encode() return result, &actionSummary{ Diagnostics: diagnostics, Facts: factsdata, FactsHash: file.HashOf(factsdata), }, nil } var ( analyzerRunTimesMu sync.Mutex analyzerRunTimes = make(map[*analysis.Analyzer]time.Duration) ) type LabelDuration struct { Label string Duration time.Duration } // AnalyzerRunTimes returns the accumulated time spent in each Analyzer's // Run function since process start, in descending order. func AnalyzerRunTimes() []LabelDuration { analyzerRunTimesMu.Lock() defer analyzerRunTimesMu.Unlock() slice := make([]LabelDuration, 0, len(analyzerRunTimes)) for a, t := range analyzerRunTimes { slice = append(slice, LabelDuration{Label: a.Name, Duration: t}) } sort.Slice(slice, func(i, j int) bool { return slice[i].Duration > slice[j].Duration }) return slice } // requiredAnalyzers returns the transitive closure of required analyzers in preorder. func requiredAnalyzers(analyzers []*analysis.Analyzer) []*analysis.Analyzer { var result []*analysis.Analyzer seen := make(map[*analysis.Analyzer]bool) var visitAll func([]*analysis.Analyzer) visitAll = func(analyzers []*analysis.Analyzer) { for _, a := range analyzers { if !seen[a] { seen[a] = true result = append(result, a) visitAll(a.Requires) } } } visitAll(analyzers) return result } var analyzeSummaryCodec = frob.CodecFor[*analyzeSummary]() // -- data types for serialization of analysis.Diagnostic and golang.Diagnostic -- // (The name says gob but we use frob.) var diagnosticsCodec = frob.CodecFor[[]gobDiagnostic]() type gobDiagnostic struct { Location protocol.Location Severity protocol.DiagnosticSeverity Code string CodeHref string Source string Message string SuggestedFixes []gobSuggestedFix Related []gobRelatedInformation Tags []protocol.DiagnosticTag } type gobRelatedInformation struct { Location protocol.Location Message string } type gobSuggestedFix struct { Message string TextEdits []gobTextEdit Command *gobCommand ActionKind protocol.CodeActionKind } type gobCommand struct { Title string Command string Arguments []json.RawMessage } type gobTextEdit struct { Location protocol.Location NewText []byte } // toGobDiagnostic converts an analysis.Diagnosic to a serializable gobDiagnostic, // which requires expanding token.Pos positions into protocol.Location form. func toGobDiagnostic(posToLocation func(start, end token.Pos) (protocol.Location, error), a *analysis.Analyzer, diag analysis.Diagnostic) (gobDiagnostic, error) { var fixes []gobSuggestedFix for _, fix := range diag.SuggestedFixes { var gobEdits []gobTextEdit for _, textEdit := range fix.TextEdits { loc, err := posToLocation(textEdit.Pos, textEdit.End) if err != nil { return gobDiagnostic{}, fmt.Errorf("in SuggestedFixes: %w", err) } gobEdits = append(gobEdits, gobTextEdit{ Location: loc, NewText: textEdit.NewText, }) } fixes = append(fixes, gobSuggestedFix{ Message: fix.Message, TextEdits: gobEdits, }) } var related []gobRelatedInformation for _, r := range diag.Related { loc, err := posToLocation(r.Pos, r.End) if err != nil { return gobDiagnostic{}, fmt.Errorf("in Related: %w", err) } related = append(related, gobRelatedInformation{ Location: loc, Message: r.Message, }) } loc, err := posToLocation(diag.Pos, diag.End) if err != nil { return gobDiagnostic{}, err } // The Code column of VSCode's Problems table renders this // information as "Source(Code)" where code is a link to CodeHref. // (The code field must be nonempty for anything to appear.) diagURL := effectiveURL(a, diag) code := "default" if diag.Category != "" { code = diag.Category } return gobDiagnostic{ Location: loc, // Severity for analysis diagnostics is dynamic, // based on user configuration per analyzer. Code: code, CodeHref: diagURL, Source: a.Name, Message: diag.Message, SuggestedFixes: fixes, Related: related, // Analysis diagnostics do not contain tags. }, nil } // effectiveURL computes the effective URL of diag, // using the algorithm specified at Diagnostic.URL. func effectiveURL(a *analysis.Analyzer, diag analysis.Diagnostic) string { u := diag.URL if u == "" && diag.Category != "" { u = "#" + diag.Category } if base, err := urlpkg.Parse(a.URL); err == nil { if rel, err := urlpkg.Parse(u); err == nil { u = base.ResolveReference(rel).String() } } return u } // stableName returns a name for the analyzer that is unique and // stable across address spaces. // // Analyzer names are not unique. For example, gopls includes // both x/tools/passes/nilness and staticcheck/nilness. // For serialization, we must assign each analyzer a unique identifier // that two gopls processes accessing the cache can agree on. func stableName(a *analysis.Analyzer) string { // Incorporate the file and line of the analyzer's Run function. addr := reflect.ValueOf(a.Run).Pointer() fn := runtime.FuncForPC(addr) file, line := fn.FileLine(addr) // It is tempting to use just a.Name as the stable name when // it is unique, but making them always differ helps avoid // name/stablename confusion. return fmt.Sprintf("%s(%s:%d)", a.Name, filepath.Base(file), line) }
tools/gopls/internal/cache/analysis.go/0
{ "file_path": "tools/gopls/internal/cache/analysis.go", "repo_id": "tools", "token_count": 19984 }
731
// 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 ( "bytes" "context" "errors" "fmt" "path/filepath" "sort" "strings" "sync/atomic" "time" "golang.org/x/tools/go/packages" "golang.org/x/tools/gopls/internal/cache/metadata" "golang.org/x/tools/gopls/internal/file" "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/immutable" "golang.org/x/tools/gopls/internal/util/pathutil" "golang.org/x/tools/gopls/internal/util/slices" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" "golang.org/x/tools/internal/xcontext" ) var loadID uint64 // atomic identifier for loads // errNoPackages indicates that a load query matched no packages. var errNoPackages = errors.New("no packages returned") // load calls packages.Load for the given scopes, updating package metadata, // import graph, and mapped files with the result. // // The resulting error may wrap the moduleErrorMap error type, representing // errors associated with specific modules. // // If scopes contains a file scope there must be exactly one scope. func (s *Snapshot) load(ctx context.Context, allowNetwork bool, scopes ...loadScope) (err error) { if ctx.Err() != nil { // Check context cancellation before incrementing id below: a load on a // cancelled context should be a no-op. return ctx.Err() } id := atomic.AddUint64(&loadID, 1) eventName := fmt.Sprintf("go/packages.Load #%d", id) // unique name for logging var query []string var standalone bool // whether this is a load of a standalone file // Keep track of module query -> module path so that we can later correlate query // errors with errors. moduleQueries := make(map[string]string) for _, scope := range scopes { switch scope := scope.(type) { case packageLoadScope: // The only time we pass package paths is when we're doing a // partial workspace load. In those cases, the paths came back from // go list and should already be GOPATH-vendorized when appropriate. query = append(query, string(scope)) case fileLoadScope: // Given multiple scopes, the resulting load might contain inaccurate // information. For example go/packages returns at most one command-line // arguments package, and does not handle a combination of standalone // files and packages. uri := protocol.DocumentURI(scope) if len(scopes) > 1 { panic(fmt.Sprintf("internal error: load called with multiple scopes when a file scope is present (file: %s)", uri)) } fh := s.FindFile(uri) if fh == nil || s.FileKind(fh) != file.Go { // Don't try to load a file that doesn't exist, or isn't a go file. continue } contents, err := fh.Content() if err != nil { continue } if isStandaloneFile(contents, s.Options().StandaloneTags) { standalone = true query = append(query, uri.Path()) } else { query = append(query, fmt.Sprintf("file=%s", uri.Path())) } case moduleLoadScope: modQuery := fmt.Sprintf("%s%c...", scope.dir, filepath.Separator) query = append(query, modQuery) moduleQueries[modQuery] = scope.modulePath case viewLoadScope: // If we are outside of GOPATH, a module, or some other known // build system, don't load subdirectories. if s.view.typ == AdHocView { query = append(query, "./") } else { query = append(query, "./...") } default: panic(fmt.Sprintf("unknown scope type %T", scope)) } } if len(query) == 0 { return nil } sort.Strings(query) // for determinism ctx, done := event.Start(ctx, "cache.snapshot.load", label.Query.Of(query)) defer done() startTime := time.Now() inv, cleanupInvocation, err := s.GoCommandInvocation(allowNetwork, &gocommand.Invocation{ WorkingDir: s.view.root.Path(), }) if err != nil { return err } defer cleanupInvocation() // Set a last resort deadline on packages.Load since it calls the go // command, which may hang indefinitely if it has a bug. golang/go#42132 // and golang/go#42255 have more context. ctx, cancel := context.WithTimeout(ctx, 10*time.Minute) defer cancel() cfg := s.config(ctx, inv) pkgs, err := packages.Load(cfg, query...) // If the context was canceled, return early. Otherwise, we might be // type-checking an incomplete result. Check the context directly, // because go/packages adds extra information to the error. if ctx.Err() != nil { return ctx.Err() } // This log message is sought for by TestReloadOnlyOnce. { lbls := append(s.Labels(), label.Query.Of(query), label.PackageCount.Of(len(pkgs)), label.Duration.Of(time.Since(startTime)), ) if err != nil { event.Error(ctx, eventName, err, lbls...) } else { event.Log(ctx, eventName, lbls...) } } if standalone { // Handle standalone package result. // // In general, this should just be a single "command-line-arguments" // package containing the requested file. However, if the file is a test // file, go/packages may return test variants of the command-line-arguments // package. We don't support this; theoretically we could, but it seems // unnecessarily complicated. // // Prior to golang/go#64233 we just assumed that we'd get exactly one // package here. The categorization of bug reports below may be a bit // verbose, but anticipates that perhaps we don't fully understand // possible failure modes. errorf := bug.Errorf if s.view.typ == GoPackagesDriverView { errorf = fmt.Errorf // all bets are off } var standalonePkg *packages.Package for _, pkg := range pkgs { if pkg.ID == "command-line-arguments" { if standalonePkg != nil { return errorf("internal error: go/packages returned multiple standalone packages") } standalonePkg = pkg } else if packagesinternal.GetForTest(pkg) == "" && !strings.HasSuffix(pkg.ID, ".test") { return errorf("internal error: go/packages returned unexpected package %q for standalone file", pkg.ID) } } if standalonePkg == nil { return errorf("internal error: go/packages failed to return non-test standalone package") } if len(standalonePkg.CompiledGoFiles) > 0 { pkgs = []*packages.Package{standalonePkg} } else { pkgs = nil } } if len(pkgs) == 0 { if err == nil { err = errNoPackages } return fmt.Errorf("packages.Load error: %w", err) } moduleErrs := make(map[string][]packages.Error) // module path -> errors filterFunc := s.view.filterFunc() newMetadata := make(map[PackageID]*metadata.Package) for _, pkg := range pkgs { if pkg.Module != nil && strings.Contains(pkg.Module.Path, "command-line-arguments") { // golang/go#61543: modules containing "command-line-arguments" cause // gopls to get all sorts of confused, because anything containing the // string "command-line-arguments" is treated as a script. And yes, this // happened in practice! (https://xkcd.com/327). Rather than try to work // around this very rare edge case, just fail loudly. return fmt.Errorf(`load failed: module name in %s contains "command-line-arguments", which is disallowed`, pkg.Module.GoMod) } // The Go command returns synthetic list results for module queries that // encountered module errors. // // For example, given a module path a.mod, we'll query for "a.mod/..." and // the go command will return a package named "a.mod/..." holding this // error. Save it for later interpretation. // // See golang/go#50862 for more details. if mod := moduleQueries[pkg.PkgPath]; mod != "" { // a synthetic result for the unloadable module if len(pkg.Errors) > 0 { moduleErrs[mod] = pkg.Errors } continue } if s.Options().VerboseOutput { event.Log(ctx, eventName, append( s.Labels(), label.Package.Of(pkg.ID), label.Files.Of(pkg.CompiledGoFiles))...) } // Ignore packages with no sources, since we will never be able to // correctly invalidate that metadata. if len(pkg.GoFiles) == 0 && len(pkg.CompiledGoFiles) == 0 { continue } // Special case for the builtin package, as it has no dependencies. if pkg.PkgPath == "builtin" { if len(pkg.GoFiles) != 1 { return fmt.Errorf("only expected 1 file for builtin, got %v", len(pkg.GoFiles)) } s.setBuiltin(pkg.GoFiles[0]) continue } // Skip test main packages. if isTestMain(pkg, s.view.folder.Env.GOCACHE) { continue } // Skip filtered packages. They may be added anyway if they're // dependencies of non-filtered packages. // // TODO(rfindley): why exclude metadata arbitrarily here? It should be safe // to capture all metadata. // TODO(rfindley): what about compiled go files? if allFilesExcluded(pkg.GoFiles, filterFunc) { continue } buildMetadata(newMetadata, pkg, cfg.Dir, standalone, s.view.typ != GoPackagesDriverView) } s.mu.Lock() // Assert the invariant s.packages.Get(id).m == s.meta.metadata[id]. s.packages.Range(func(id PackageID, ph *packageHandle) { if s.meta.Packages[id] != ph.mp { panic("inconsistent metadata") } }) // Compute the minimal metadata updates (for Clone) // required to preserve the above invariant. var files []protocol.DocumentURI // files to preload seenFiles := make(map[protocol.DocumentURI]bool) updates := make(map[PackageID]*metadata.Package) for _, mp := range newMetadata { if existing := s.meta.Packages[mp.ID]; existing == nil { // Record any new files we should pre-load. for _, uri := range mp.CompiledGoFiles { if !seenFiles[uri] { seenFiles[uri] = true files = append(files, uri) } } updates[mp.ID] = mp s.shouldLoad.Delete(mp.ID) } } if s.Options().VerboseOutput { event.Log(ctx, fmt.Sprintf("%s: updating metadata for %d packages", eventName, len(updates))) } meta := s.meta.Update(updates) workspacePackages := computeWorkspacePackagesLocked(ctx, s, meta) s.meta = meta s.workspacePackages = workspacePackages s.resetActivePackagesLocked() s.mu.Unlock() // Opt: preLoad files in parallel. // // Requesting files in batch optimizes the underlying filesystem reads. // However, this is also currently necessary for correctness: populating all // files in the snapshot is necessary for certain operations that rely on the // completeness of the file map, e.g. computing the set of directories to // watch. // // TODO(rfindley, golang/go#57558): determine the set of directories based on // loaded packages, so that reading files here is not necessary for // correctness. s.preloadFiles(ctx, files) if len(moduleErrs) > 0 { return &moduleErrorMap{moduleErrs} } return nil } type moduleErrorMap struct { errs map[string][]packages.Error // module path -> errors } func (m *moduleErrorMap) Error() string { var paths []string // sort for stability for path, errs := range m.errs { if len(errs) > 0 { // should always be true, but be cautious paths = append(paths, path) } } sort.Strings(paths) var buf bytes.Buffer fmt.Fprintf(&buf, "%d modules have errors:\n", len(paths)) for _, path := range paths { fmt.Fprintf(&buf, "\t%s:%s\n", path, m.errs[path][0].Msg) } return buf.String() } // buildMetadata populates the updates map with metadata updates to // apply, based on the given pkg. It recurs through pkg.Imports to ensure that // metadata exists for all dependencies. // // Returns the metadata.Package that was built (or which was already present in // updates), or nil if the package could not be built. Notably, the resulting // metadata.Package may have an ID that differs from pkg.ID. func buildMetadata(updates map[PackageID]*metadata.Package, pkg *packages.Package, loadDir string, standalone, goListView bool) *metadata.Package { // Allow for multiple ad-hoc packages in the workspace (see #47584). pkgPath := PackagePath(pkg.PkgPath) id := PackageID(pkg.ID) // debugging #60890 if pkg.PkgPath == "unsafe" && pkg.ID != "unsafe" { bug.Reportf("PackagePath \"unsafe\" with ID %q", pkg.ID) } if metadata.IsCommandLineArguments(id) { var f string // file to use as disambiguating suffix if len(pkg.CompiledGoFiles) > 0 { f = pkg.CompiledGoFiles[0] // If there are multiple files, // we can't use only the first. // (Can this happen? #64557) if len(pkg.CompiledGoFiles) > 1 { bug.Reportf("unexpected files in command-line-arguments package: %v", pkg.CompiledGoFiles) return nil } } else if len(pkg.IgnoredFiles) > 0 { // A file=empty.go query results in IgnoredFiles=[empty.go]. f = pkg.IgnoredFiles[0] } else { bug.Reportf("command-line-arguments package has neither CompiledGoFiles nor IgnoredFiles") return nil } id = PackageID(pkg.ID + f) pkgPath = PackagePath(pkg.PkgPath + f) } // Duplicate? if existing, ok := updates[id]; ok { // A package was encountered twice due to shared // subgraphs (common) or cycles (rare). Although "go // list" usually breaks cycles, we don't rely on it. // breakImportCycles in metadataGraph.Clone takes care // of it later. return existing } if pkg.TypesSizes == nil { panic(id + ".TypeSizes is nil") } // Recreate the metadata rather than reusing it to avoid locking. mp := &metadata.Package{ ID: id, PkgPath: pkgPath, Name: PackageName(pkg.Name), ForTest: PackagePath(packagesinternal.GetForTest(pkg)), TypesSizes: pkg.TypesSizes, LoadDir: loadDir, Module: pkg.Module, Errors: pkg.Errors, DepsErrors: packagesinternal.GetDepsErrors(pkg), Standalone: standalone, } // debugging #60890 if mp.PkgPath == "unsafe" && mp.ID != "unsafe" { bug.Reportf("PackagePath \"unsafe\" with ID %q", mp.ID) } updates[id] = mp for _, filename := range pkg.CompiledGoFiles { uri := protocol.URIFromPath(filename) mp.CompiledGoFiles = append(mp.CompiledGoFiles, uri) } for _, filename := range pkg.GoFiles { uri := protocol.URIFromPath(filename) mp.GoFiles = append(mp.GoFiles, uri) } for _, filename := range pkg.IgnoredFiles { uri := protocol.URIFromPath(filename) mp.IgnoredFiles = append(mp.IgnoredFiles, uri) } depsByImpPath := make(map[ImportPath]PackageID) depsByPkgPath := make(map[PackagePath]PackageID) for importPath, imported := range pkg.Imports { importPath := ImportPath(importPath) // It is not an invariant that importPath == imported.PkgPath. // For example, package "net" imports "golang.org/x/net/dns/dnsmessage" // which refers to the package whose ID and PkgPath are both // "vendor/golang.org/x/net/dns/dnsmessage". Notice the ImportMap, // which maps ImportPaths to PackagePaths: // // $ go list -json net vendor/golang.org/x/net/dns/dnsmessage // { // "ImportPath": "net", // "Name": "net", // "Imports": [ // "C", // "vendor/golang.org/x/net/dns/dnsmessage", // "vendor/golang.org/x/net/route", // ... // ], // "ImportMap": { // "golang.org/x/net/dns/dnsmessage": "vendor/golang.org/x/net/dns/dnsmessage", // "golang.org/x/net/route": "vendor/golang.org/x/net/route" // }, // ... // } // { // "ImportPath": "vendor/golang.org/x/net/dns/dnsmessage", // "Name": "dnsmessage", // ... // } // // (Beware that, for historical reasons, go list uses // the JSON field "ImportPath" for the package's // path--effectively the linker symbol prefix.) // // The example above is slightly special to go list // because it's in the std module. Otherwise, // vendored modules are simply modules whose directory // is vendor/ instead of GOMODCACHE, and the // import path equals the package path. // // But in GOPATH (non-module) mode, it's possible for // package vendoring to cause a non-identity ImportMap, // as in this example: // // $ cd $HOME/src // $ find . -type f // ./b/b.go // ./vendor/example.com/a/a.go // $ cat ./b/b.go // package b // import _ "example.com/a" // $ cat ./vendor/example.com/a/a.go // package a // $ GOPATH=$HOME GO111MODULE=off go list -json ./b | grep -A2 ImportMap // "ImportMap": { // "example.com/a": "vendor/example.com/a" // }, // Don't remember any imports with significant errors. // // The len=0 condition is a heuristic check for imports of // non-existent packages (for which go/packages will create // an edge to a synthesized node). The heuristic is unsound // because some valid packages have zero files, for example, // a directory containing only the file p_test.go defines an // empty package p. // TODO(adonovan): clarify this. Perhaps go/packages should // report which nodes were synthesized. if importPath != "unsafe" && len(imported.CompiledGoFiles) == 0 { depsByImpPath[importPath] = "" // missing continue } // Don't record self-import edges. // (This simplifies metadataGraph's cycle check.) if PackageID(imported.ID) == id { if len(pkg.Errors) == 0 { bug.Reportf("self-import without error in package %s", id) } continue } dep := buildMetadata(updates, imported, loadDir, false, goListView) // only top level packages can be standalone // Don't record edges to packages with no name, as they cause trouble for // the importer (golang/go#60952). // // Also don't record edges to packages whose ID was modified (i.e. // command-line-arguments packages), as encountered in golang/go#66109. In // this case, we could theoretically keep the edge through dep.ID, but // since this import doesn't make any sense in the first place, we instead // choose to consider it invalid. // // However, we do want to insert these packages into the update map // (buildMetadata above), so that we get type-checking diagnostics for the // invalid packages. if dep == nil || dep.ID != PackageID(imported.ID) || imported.Name == "" { depsByImpPath[importPath] = "" // missing continue } depsByImpPath[importPath] = PackageID(imported.ID) depsByPkgPath[PackagePath(imported.PkgPath)] = PackageID(imported.ID) } mp.DepsByImpPath = depsByImpPath mp.DepsByPkgPath = depsByPkgPath return mp // m.Diagnostics is set later in the loading pass, using // computeLoadDiagnostics. } // computeLoadDiagnostics computes and sets m.Diagnostics for the given metadata m. // // It should only be called during package handle construction in buildPackageHandle. func computeLoadDiagnostics(ctx context.Context, snapshot *Snapshot, mp *metadata.Package) []*Diagnostic { var diags []*Diagnostic for _, packagesErr := range mp.Errors { // Filter out parse errors from go list. We'll get them when we // actually parse, and buggy overlay support may generate spurious // errors. (See TestNewModule_Issue38207.) if strings.Contains(packagesErr.Msg, "expected '") { continue } pkgDiags, err := goPackagesErrorDiagnostics(ctx, packagesErr, mp, snapshot) if err != nil { // There are certain cases where the go command returns invalid // positions, so we cannot panic or even bug.Reportf here. event.Error(ctx, "unable to compute positions for list errors", err, label.Package.Of(string(mp.ID))) continue } diags = append(diags, pkgDiags...) } // TODO(rfindley): this is buggy: an insignificant change to a modfile // (or an unsaved modfile) could affect the position of deps errors, // without invalidating the package. depsDiags, err := depsErrors(ctx, snapshot, mp) if err != nil { if ctx.Err() == nil { // TODO(rfindley): consider making this a bug.Reportf. depsErrors should // not normally fail. event.Error(ctx, "unable to compute deps errors", err, label.Package.Of(string(mp.ID))) } } else { diags = append(diags, depsDiags...) } return diags } // IsWorkspacePackage reports whether id points to a workspace package in s. // // Currently, the result depends on the current set of loaded packages, and so // is not guaranteed to be stable. func (s *Snapshot) IsWorkspacePackage(ctx context.Context, id PackageID) bool { s.mu.Lock() defer s.mu.Unlock() mg := s.meta m := mg.Packages[id] if m == nil { return false } return isWorkspacePackageLocked(ctx, s, mg, m) } // isWorkspacePackageLocked reports whether p is a workspace package for the // snapshot s. // // Workspace packages are packages that we consider the user to be actively // working on. As such, they are re-diagnosed on every keystroke, and searched // for various workspace-wide queries such as references or workspace symbols. // // See the commentary inline for a description of the workspace package // heuristics. // // s.mu must be held while calling this function. // // TODO(rfindley): remove 'meta' from this function signature. Whether or not a // package is a workspace package should depend only on the package, view // definition, and snapshot file source. While useful, the heuristic // "allFilesHaveRealPackages" does not add that much value and is path // dependent as it depends on the timing of loads. func isWorkspacePackageLocked(ctx context.Context, s *Snapshot, meta *metadata.Graph, pkg *metadata.Package) bool { if metadata.IsCommandLineArguments(pkg.ID) { // Ad-hoc command-line-arguments packages aren't workspace packages. // With zero-config gopls (golang/go#57979) they should be very rare, as // they should only arise when the user opens a file outside the workspace // which isn't present in the import graph of a workspace package. // // Considering them as workspace packages tends to be racy, as they don't // deterministically belong to any view. if !pkg.Standalone { return false } // If all the files contained in pkg have a real package, we don't need to // keep pkg as a workspace package. if allFilesHaveRealPackages(meta, pkg) { return false } // For now, allow open standalone packages (i.e. go:build ignore) to be // workspace packages, but this means they could belong to multiple views. return containsOpenFileLocked(s, pkg) } // If a real package is open, consider it to be part of the workspace. // // TODO(rfindley): reconsider this. In golang/go#66145, we saw that even if a // View sees a real package for a file, it doesn't mean that View is able to // cleanly diagnose the package. Yet, we do want to show diagnostics for open // packages outside the workspace. Is there a better way to ensure that only // the 'best' View gets a workspace package for the open file? if containsOpenFileLocked(s, pkg) { return true } // Apply filtering logic. // // Workspace packages must contain at least one non-filtered file. filterFunc := s.view.filterFunc() uris := make(map[protocol.DocumentURI]unit) // filtered package URIs for _, uri := range slices.Concat(pkg.CompiledGoFiles, pkg.GoFiles) { if !strings.Contains(string(uri), "/vendor/") && !filterFunc(uri) { uris[uri] = struct{}{} } } if len(uris) == 0 { return false // no non-filtered files } // For non-module views (of type GOPATH or AdHoc), or if // expandWorkspaceToModule is unset, workspace packages must be contained in // the workspace folder. // // For module views (of type GoMod or GoWork), packages must in any case be // in a workspace module (enforced below). if !s.view.typ.usesModules() || !s.Options().ExpandWorkspaceToModule { folder := s.view.folder.Dir.Path() inFolder := false for uri := range uris { if pathutil.InDir(folder, uri.Path()) { inFolder = true break } } if !inFolder { return false } } // In module mode, a workspace package must be contained in a workspace // module. if s.view.typ.usesModules() { var modURI protocol.DocumentURI if pkg.Module != nil { modURI = protocol.URIFromPath(pkg.Module.GoMod) } else { // golang/go#65816: for std and cmd, Module is nil. // Fall back to an inferior heuristic. if len(pkg.CompiledGoFiles) == 0 { return false // need at least one file to guess the go.mod file } dir := pkg.CompiledGoFiles[0].Dir() var err error modURI, err = findRootPattern(ctx, dir, "go.mod", lockedSnapshot{s}) if err != nil || modURI == "" { // err != nil implies context cancellation, in which case the result of // this query does not matter. return false } } _, ok := s.view.workspaceModFiles[modURI] return ok } return true // an ad-hoc package or GOPATH package } // containsOpenFileLocked reports whether any file referenced by m is open in // the snapshot s. // // s.mu must be held while calling this function. func containsOpenFileLocked(s *Snapshot, mp *metadata.Package) bool { 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 { fh, _ := s.files.get(uri) if _, open := fh.(*overlay); open { return true } } return false } // computeWorkspacePackagesLocked computes workspace packages in the // snapshot s for the given metadata graph. The result does not // contain intermediate test variants. // // s.mu must be held while calling this function. func computeWorkspacePackagesLocked(ctx context.Context, s *Snapshot, meta *metadata.Graph) immutable.Map[PackageID, PackagePath] { // The provided context is used for reading snapshot files, which can only // fail due to context cancellation. Don't let this happen as it could lead // to inconsistent results. ctx = xcontext.Detach(ctx) workspacePackages := make(map[PackageID]PackagePath) for _, mp := range meta.Packages { if !isWorkspacePackageLocked(ctx, s, meta, mp) { continue } switch { case mp.ForTest == "": // A normal package. workspacePackages[mp.ID] = mp.PkgPath case mp.ForTest == mp.PkgPath, mp.ForTest+"_test" == mp.PkgPath: // The test variant of some workspace package or its x_test. // To load it, we need to load the non-test variant with -test. // // Notably, this excludes intermediate test variants from workspace // packages. assert(!mp.IsIntermediateTestVariant(), "unexpected ITV") workspacePackages[mp.ID] = mp.ForTest } } return immutable.MapOf(workspacePackages) } // allFilesHaveRealPackages reports whether all files referenced by m are // contained in a "real" package (not command-line-arguments). // // If m is valid but all "real" packages containing any file are invalid, this // function returns false. // // If m is not a command-line-arguments package, this is trivially true. func allFilesHaveRealPackages(g *metadata.Graph, mp *metadata.Package) bool { n := len(mp.CompiledGoFiles) checkURIs: for _, uri := range append(mp.CompiledGoFiles[0:n:n], mp.GoFiles...) { for _, id := range g.IDs[uri] { if !metadata.IsCommandLineArguments(id) { continue checkURIs } } return false } return true } func isTestMain(pkg *packages.Package, gocache string) bool { // Test mains must have an import path that ends with ".test". if !strings.HasSuffix(pkg.PkgPath, ".test") { return false } // Test main packages are always named "main". if pkg.Name != "main" { return false } // Test mains always have exactly one GoFile that is in the build cache. if len(pkg.GoFiles) > 1 { return false } if !pathutil.InDir(gocache, pkg.GoFiles[0]) { return false } return true }
tools/gopls/internal/cache/load.go/0
{ "file_path": "tools/gopls/internal/cache/load.go", "repo_id": "tools", "token_count": 9557 }
732
// 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 parsego_test import ( "context" "go/ast" "go/token" "testing" "golang.org/x/tools/gopls/internal/cache/parsego" "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/tokeninternal" ) // TODO(golang/go#64335): we should have many more tests for fixed syntax. func TestFixPosition_Issue64488(t *testing.T) { // This test reproduces the conditions of golang/go#64488, where a type error // on fixed syntax overflows the token.File. const src = ` package foo func _() { type myThing struct{} var foo []myThing for ${1:}, ${2:} := range foo { $0 } } ` pgf, _ := parsego.Parse(context.Background(), token.NewFileSet(), "file://foo.go", []byte(src), parsego.Full, false) fset := tokeninternal.FileSetFor(pgf.Tok) ast.Inspect(pgf.File, func(n ast.Node) bool { if n != nil { posn := safetoken.StartPosition(fset, n.Pos()) if !posn.IsValid() { t.Fatalf("invalid position for %T (%v): %v not in [%d, %d]", n, n, n.Pos(), pgf.Tok.Base(), pgf.Tok.Base()+pgf.Tok.Size()) } } return true }) }
tools/gopls/internal/cache/parsego/parse_test.go/0
{ "file_path": "tools/gopls/internal/cache/parsego/parse_test.go", "repo_id": "tools", "token_count": 482 }
733
// 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 xrefs defines the serializable index of cross-package // references that is computed during type checking. // // See ../references.go for the 'references' query. package xrefs import ( "go/ast" "go/types" "sort" "golang.org/x/tools/go/types/objectpath" "golang.org/x/tools/gopls/internal/cache/metadata" "golang.org/x/tools/gopls/internal/cache/parsego" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/util/frob" "golang.org/x/tools/gopls/internal/util/typesutil" ) // Index constructs a serializable index of outbound cross-references // for the specified type-checked package. func Index(files []*parsego.File, pkg *types.Package, info *types.Info) []byte { // pkgObjects maps each referenced package Q to a mapping: // from each referenced symbol in Q to the ordered list // of references to that symbol from this package. // A nil types.Object indicates a reference // to the package as a whole: an import. pkgObjects := make(map[*types.Package]map[types.Object]*gobObject) // getObjects returns the object-to-references mapping for a package. getObjects := func(pkg *types.Package) map[types.Object]*gobObject { objects, ok := pkgObjects[pkg] if !ok { objects = make(map[types.Object]*gobObject) pkgObjects[pkg] = objects } return objects } objectpathFor := new(objectpath.Encoder).For for fileIndex, pgf := range files { nodeRange := func(n ast.Node) protocol.Range { rng, err := pgf.PosRange(n.Pos(), n.End()) if err != nil { panic(err) // can't fail } return rng } ast.Inspect(pgf.File, func(n ast.Node) bool { switch n := n.(type) { case *ast.Ident: // Report a reference for each identifier that // uses a symbol exported from another package. // (The built-in error.Error method has no package.) if n.IsExported() { if obj, ok := info.Uses[n]; ok && obj.Pkg() != nil && obj.Pkg() != pkg { // For instantiations of generic methods, // use the generic object (see issue #60622). if fn, ok := obj.(*types.Func); ok { obj = fn.Origin() } objects := getObjects(obj.Pkg()) gobObj, ok := objects[obj] if !ok { path, err := objectpathFor(obj) if err != nil { // Capitalized but not exported // (e.g. local const/var/type). return true } gobObj = &gobObject{Path: path} objects[obj] = gobObj } gobObj.Refs = append(gobObj.Refs, gobRef{ FileIndex: fileIndex, Range: nodeRange(n), }) } } case *ast.ImportSpec: // Report a reference from each import path // string to the imported package. pkgname, ok := typesutil.ImportedPkgName(info, n) if !ok { return true // missing import } objects := getObjects(pkgname.Imported()) gobObj, ok := objects[nil] if !ok { gobObj = &gobObject{Path: ""} objects[nil] = gobObj } gobObj.Refs = append(gobObj.Refs, gobRef{ FileIndex: fileIndex, Range: nodeRange(n.Path), }) } return true }) } // Flatten the maps into slices, and sort for determinism. var packages []*gobPackage for p := range pkgObjects { objects := pkgObjects[p] gp := &gobPackage{ PkgPath: metadata.PackagePath(p.Path()), Objects: make([]*gobObject, 0, len(objects)), } for _, gobObj := range objects { gp.Objects = append(gp.Objects, gobObj) } sort.Slice(gp.Objects, func(i, j int) bool { return gp.Objects[i].Path < gp.Objects[j].Path }) packages = append(packages, gp) } sort.Slice(packages, func(i, j int) bool { return packages[i].PkgPath < packages[j].PkgPath }) return packageCodec.Encode(packages) } // Lookup searches a serialized index produced by an indexPackage // operation on m, and returns the locations of all references from m // to any object in the target set. Each object is denoted by a pair // of (package path, object path). func Lookup(mp *metadata.Package, data []byte, targets map[metadata.PackagePath]map[objectpath.Path]struct{}) (locs []protocol.Location) { var packages []*gobPackage packageCodec.Decode(data, &packages) for _, gp := range packages { if objectSet, ok := targets[gp.PkgPath]; ok { for _, gobObj := range gp.Objects { if _, ok := objectSet[gobObj.Path]; ok { for _, ref := range gobObj.Refs { uri := mp.CompiledGoFiles[ref.FileIndex] locs = append(locs, protocol.Location{ URI: uri, Range: ref.Range, }) } } } } } return locs } // -- serialized representation -- // The cross-reference index records the location of all references // from one package to symbols defined in other packages // (dependencies). It does not record within-package references. // The index for package P consists of a list of gopPackage records, // each enumerating references to symbols defined a single dependency, Q. // TODO(adonovan): opt: choose a more compact encoding. // The gobRef.Range field is the obvious place to begin. // (The name says gob but in fact we use frob.) var packageCodec = frob.CodecFor[[]*gobPackage]() // A gobPackage records the set of outgoing references from the index // package to symbols defined in a dependency package. type gobPackage struct { PkgPath metadata.PackagePath // defining package (Q) Objects []*gobObject // set of Q objects referenced by P } // A gobObject records all references to a particular symbol. type gobObject struct { Path objectpath.Path // symbol name within package; "" => import of package itself Refs []gobRef // locations of references within P, in lexical order } type gobRef struct { FileIndex int // index of enclosing file within P's CompiledGoFiles Range protocol.Range // source range of reference }
tools/gopls/internal/cache/xrefs/xrefs.go/0
{ "file_path": "tools/gopls/internal/cache/xrefs/xrefs.go", "repo_id": "tools", "token_count": 2234 }
734
// 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 cmdtest contains the test suite for the command line behavior of gopls. package cmd_test // This file defines integration tests of each gopls subcommand that // fork+exec the command in a separate process. // // (Rather than execute 'go build gopls' during the test, we reproduce // the main entrypoint in the test executable.) // // The purpose of this test is to exercise client-side logic such as // argument parsing and formatting of LSP RPC responses, not server // behavior; see lsp_test for that. // // All tests run in parallel. // // TODO(adonovan): // - Use markers to represent positions in the input and in assertions. // - Coverage of cross-cutting things like cwd, environ, span parsing, etc. // - Subcommands that accept -write and -diff flags implement them // consistently; factor their tests. // - Add missing test for 'vulncheck' subcommand. // - Add tests for client-only commands: serve, bug, help, api-json, licenses. import ( "bytes" "context" "encoding/json" "fmt" "math/rand" "os" "os/exec" "path/filepath" "regexp" "strings" "testing" "golang.org/x/tools/gopls/internal/cmd" "golang.org/x/tools/gopls/internal/debug" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/util/bug" "golang.org/x/tools/gopls/internal/version" "golang.org/x/tools/internal/testenv" "golang.org/x/tools/internal/tool" "golang.org/x/tools/txtar" ) // TestVersion tests the 'version' subcommand (../info.go). func TestVersion(t *testing.T) { t.Parallel() tree := writeTree(t, "") // There's not much we can robustly assert about the actual version. want := version.Version() // e.g. "master" // basic { res := gopls(t, tree, "version") res.checkExit(true) res.checkStdout(want) } // basic, with version override { res := goplsWithEnv(t, tree, []string{"TEST_GOPLS_VERSION=v1.2.3"}, "version") res.checkExit(true) res.checkStdout(`v1\.2\.3`) } // -json flag { res := gopls(t, tree, "version", "-json") res.checkExit(true) var v debug.ServerVersion if res.toJSON(&v) { if v.Version != want { t.Errorf("expected Version %q, got %q (%v)", want, v.Version, res) } } } } // TestCheck tests the 'check' subcommand (../check.go). func TestCheck(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a import "fmt" var _ = fmt.Sprintf("%s", 123) -- b.go -- package a import "fmt" var _ = fmt.Sprintf("%d", "123") -- c/c.go -- package c var C int -- c/c2.go -- package c var C int `) // no files { res := gopls(t, tree, "check") res.checkExit(true) if res.stdout != "" { t.Errorf("unexpected output: %v", res) } } // one file { res := gopls(t, tree, "check", "./a.go") res.checkExit(true) res.checkStdout("fmt.Sprintf format %s has arg 123 of wrong type int") } // two files { res := gopls(t, tree, "check", "./a.go", "./b.go") res.checkExit(true) res.checkStdout(`a.go:.* fmt.Sprintf format %s has arg 123 of wrong type int`) res.checkStdout(`b.go:.* fmt.Sprintf format %d has arg "123" of wrong type string`) } // diagnostic with related information spanning files { res := gopls(t, tree, "check", "./c/c2.go") res.checkExit(true) res.checkStdout(`c2.go:2:5-6: C redeclared in this block`) res.checkStdout(`c.go:2:5-6: - other declaration of C`) } } // TestCallHierarchy tests the 'call_hierarchy' subcommand (../call_hierarchy.go). func TestCallHierarchy(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func f() {} func g() { f() } func h() { f() f() } `) // missing position { res := gopls(t, tree, "call_hierarchy") res.checkExit(false) res.checkStderr("expects 1 argument") } // wrong place { res := gopls(t, tree, "call_hierarchy", "a.go:1") res.checkExit(false) res.checkStderr("identifier not found") } // f is called once from g and twice from h. { res := gopls(t, tree, "call_hierarchy", "a.go:2:6") res.checkExit(true) // We use regexp '.' as an OS-agnostic path separator. res.checkStdout("ranges 7:2-3, 8:2-3 in ..a.go from/to function h in ..a.go:6:6-7") res.checkStdout("ranges 4:2-3 in ..a.go from/to function g in ..a.go:3:6-7") res.checkStdout("identifier: function f in ..a.go:2:6-7") } } // TestCodeLens tests the 'codelens' subcommand (../codelens.go). func TestCodeLens(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a/a.go -- package a -- a/a_test.go -- package a_test import "testing" func TestPass(t *testing.T) {} func TestFail(t *testing.T) { t.Fatal("fail") } `) // missing position { res := gopls(t, tree, "codelens") res.checkExit(false) res.checkStderr("requires a file name") } // list code lenses { res := gopls(t, tree, "codelens", "./a/a_test.go") res.checkExit(true) res.checkStdout(`a_test.go:3: "run test" \[gopls.test\]`) res.checkStdout(`a_test.go:4: "run test" \[gopls.test\]`) } // no codelens with title/position { res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:1", "nope") res.checkExit(false) res.checkStderr(`no code lens at .* with title "nope"`) } // run the passing test { res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:3", "run test") res.checkExit(true) res.checkStderr(`PASS: TestPass`) // from go test res.checkStderr("Info: all tests passed") // from gopls.test } // run the failing test { res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:4", "run test") res.checkExit(false) res.checkStderr(`FAIL example.com/a`) res.checkStderr("Info: 1 / 1 tests failed") } } // TestDefinition tests the 'definition' subcommand (../definition.go). func TestDefinition(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a import "fmt" func f() { fmt.Println() } func g() { f() } `) // missing position { res := gopls(t, tree, "definition") res.checkExit(false) res.checkStderr("expects 1 argument") } // intra-package { res := gopls(t, tree, "definition", "a.go:7:2") // "f()" res.checkExit(true) res.checkStdout("a.go:3:6-7: defined here as func f") } // cross-package { res := gopls(t, tree, "definition", "a.go:4:7") // "Println" res.checkExit(true) res.checkStdout("print.go.* defined here as func fmt.Println") res.checkStdout("Println formats using the default formats for its operands") } // -json and -markdown { res := gopls(t, tree, "definition", "-json", "-markdown", "a.go:4:7") res.checkExit(true) var defn cmd.Definition if res.toJSON(&defn) { if !strings.HasPrefix(defn.Description, "```go\nfunc fmt.Println") { t.Errorf("Description does not start with markdown code block. Got: %s", defn.Description) } } } } // TestExecute tests the 'execute' subcommand (../execute.go). func TestExecute(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- hello.go -- package a func main() {} -- hello_test.go -- package a import "testing" func TestHello(t *testing.T) { t.Fatal("oops") } `) // missing command name { res := gopls(t, tree, "execute") res.checkExit(false) res.checkStderr("requires a command") } // bad command { res := gopls(t, tree, "execute", "gopls.foo") res.checkExit(false) res.checkStderr("unrecognized command: gopls.foo") } // too few arguments { res := gopls(t, tree, "execute", "gopls.run_tests") res.checkExit(false) res.checkStderr("expected 1 input arguments, got 0") } // too many arguments { res := gopls(t, tree, "execute", "gopls.run_tests", "null", "null") res.checkExit(false) res.checkStderr("expected 1 input arguments, got 2") } // argument is not JSON { res := gopls(t, tree, "execute", "gopls.run_tests", "hello") res.checkExit(false) res.checkStderr("argument 1 is not valid JSON: invalid character 'h'") } // add import, show diff hello := "file://" + filepath.ToSlash(tree) + "/hello.go" { res := gopls(t, tree, "execute", "-d", "gopls.add_import", `{"ImportPath": "fmt", "URI": "`+hello+`"}`) res.checkExit(true) res.checkStdout(`[+]import "fmt"`) } // list known packages (has a result) { res := gopls(t, tree, "execute", "gopls.list_known_packages", `{"URI": "`+hello+`"}`) res.checkExit(true) res.checkStdout(`"fmt"`) res.checkStdout(`"encoding/json"`) } // run tests { helloTest := "file://" + filepath.ToSlash(tree) + "/hello_test.go" res := gopls(t, tree, "execute", "gopls.run_tests", `{"URI": "`+helloTest+`", "Tests": ["TestHello"]}`) res.checkExit(false) res.checkStderr(`hello_test.go:4: oops`) res.checkStderr(`1 / 1 tests failed`) } } // TestFoldingRanges tests the 'folding_ranges' subcommand (../folding_range.go). func TestFoldingRanges(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func f(x int) { // hello } `) // missing filename { res := gopls(t, tree, "folding_ranges") res.checkExit(false) res.checkStderr("expects 1 argument") } // success { res := gopls(t, tree, "folding_ranges", "a.go") res.checkExit(true) res.checkStdout("2:8-2:13") // params (x int) res.checkStdout("2:16-4:1") // body { ... } } } // TestFormat tests the 'format' subcommand (../format.go). func TestFormat(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- a.go -- package a ; func f ( ) { } `) const want = `package a func f() {} ` // no files => nop { res := gopls(t, tree, "format") res.checkExit(true) } // default => print formatted result { res := gopls(t, tree, "format", "a.go") res.checkExit(true) if res.stdout != want { t.Errorf("format: got <<%s>>, want <<%s>>", res.stdout, want) } } // start/end position not supported (unless equal to start/end of file) { res := gopls(t, tree, "format", "a.go:1-2") res.checkExit(false) res.checkStderr("only full file formatting supported") } // -list: show only file names { res := gopls(t, tree, "format", "-list", "a.go") res.checkExit(true) res.checkStdout("a.go") } // -diff prints a unified diff { res := gopls(t, tree, "format", "-diff", "a.go") res.checkExit(true) // We omit the filenames as they vary by OS. want := ` -package a ; func f ( ) { } +package a + +func f() {} ` res.checkStdout(regexp.QuoteMeta(want)) } // -write updates the file { res := gopls(t, tree, "format", "-write", "a.go") res.checkExit(true) res.checkStdout("^$") // empty checkContent(t, filepath.Join(tree, "a.go"), want) } } // TestHighlight tests the 'highlight' subcommand (../highlight.go). func TestHighlight(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- a.go -- package a import "fmt" func f() { fmt.Println() fmt.Println() } `) // no arguments { res := gopls(t, tree, "highlight") res.checkExit(false) res.checkStderr("expects 1 argument") } // all occurrences of Println { res := gopls(t, tree, "highlight", "a.go:4:7") res.checkExit(true) res.checkStdout("a.go:4:6-13") res.checkStdout("a.go:5:6-13") } } // TestImplementations tests the 'implementation' subcommand (../implementation.go). func TestImplementations(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- a.go -- package a import "fmt" type T int func (T) String() string { return "" } `) // no arguments { res := gopls(t, tree, "implementation") res.checkExit(false) res.checkStderr("expects 1 argument") } // T.String { res := gopls(t, tree, "implementation", "a.go:4:10") res.checkExit(true) // TODO(adonovan): extract and check the content of the reported ranges? // We use regexp '.' as an OS-agnostic path separator. res.checkStdout("fmt.print.go:") // fmt.Stringer.String res.checkStdout("runtime.error.go:") // runtime.stringer.String } } // TestImports tests the 'imports' subcommand (../imports.go). func TestImports(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- a.go -- package a func _() { fmt.Println() } `) want := ` package a import "fmt" func _() { fmt.Println() } `[1:] // no arguments { res := gopls(t, tree, "imports") res.checkExit(false) res.checkStderr("expects 1 argument") } // default: print with imports { res := gopls(t, tree, "imports", "a.go") res.checkExit(true) if res.stdout != want { t.Errorf("imports: got <<%s>>, want <<%s>>", res.stdout, want) } } // -diff: show a unified diff { res := gopls(t, tree, "imports", "-diff", "a.go") res.checkExit(true) res.checkStdout(regexp.QuoteMeta(`+import "fmt"`)) } // -write: update file { res := gopls(t, tree, "imports", "-write", "a.go") res.checkExit(true) checkContent(t, filepath.Join(tree, "a.go"), want) } } // TestLinks tests the 'links' subcommand (../links.go). func TestLinks(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- a.go -- // Link in package doc: https://pkg.go.dev/ package a // Link in internal comment: https://go.dev/cl // Doc comment link: https://blog.go.dev/ func f() {} `) // no arguments { res := gopls(t, tree, "links") res.checkExit(false) res.checkStderr("expects 1 argument") } // success { res := gopls(t, tree, "links", "a.go") res.checkExit(true) res.checkStdout("https://go.dev/cl") res.checkStdout("https://pkg.go.dev") res.checkStdout("https://blog.go.dev/") } // -json { res := gopls(t, tree, "links", "-json", "a.go") res.checkExit(true) res.checkStdout("https://pkg.go.dev") res.checkStdout("https://go.dev/cl") res.checkStdout("https://blog.go.dev/") // at 5:21-5:41 var links []protocol.DocumentLink if res.toJSON(&links) { // Check just one of the three locations. if got, want := fmt.Sprint(links[2].Range), "5:21-5:41"; got != want { t.Errorf("wrong link location: got %v, want %v", got, want) } } } } // TestReferences tests the 'references' subcommand (../references.go). func TestReferences(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a import "fmt" func f() { fmt.Println() } -- b.go -- package a import "fmt" func g() { fmt.Println() } `) // no arguments { res := gopls(t, tree, "references") res.checkExit(false) res.checkStderr("expects 1 argument") } // fmt.Println { res := gopls(t, tree, "references", "a.go:4:10") res.checkExit(true) res.checkStdout("a.go:4:6-13") res.checkStdout("b.go:4:6-13") } } // TestSignature tests the 'signature' subcommand (../signature.go). func TestSignature(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a import "fmt" func f() { fmt.Println(123) } `) // no arguments { res := gopls(t, tree, "signature") res.checkExit(false) res.checkStderr("expects 1 argument") } // at 123 inside fmt.Println() call { res := gopls(t, tree, "signature", "a.go:4:15") res.checkExit(true) res.checkStdout("Println\\(a ...") res.checkStdout("Println formats using the default formats...") } } // TestPrepareRename tests the 'prepare_rename' subcommand (../prepare_rename.go). func TestPrepareRename(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func oldname() {} `) // no arguments { res := gopls(t, tree, "prepare_rename") res.checkExit(false) res.checkStderr("expects 1 argument") } // in 'package' keyword { res := gopls(t, tree, "prepare_rename", "a.go:1:3") res.checkExit(false) res.checkStderr("request is not valid at the given position") } // in 'package' identifier (not supported by client) { res := gopls(t, tree, "prepare_rename", "a.go:1:9") res.checkExit(false) res.checkStderr("can't rename package") } // in func oldname { res := gopls(t, tree, "prepare_rename", "a.go:2:9") res.checkExit(true) res.checkStdout("a.go:2:6-13") // all of "oldname" } } // TestRename tests the 'rename' subcommand (../rename.go). func TestRename(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func oldname() {} `) // no arguments { res := gopls(t, tree, "rename") res.checkExit(false) res.checkStderr("expects 2 arguments") } // missing newname { res := gopls(t, tree, "rename", "a.go:1:3") res.checkExit(false) res.checkStderr("expects 2 arguments") } // in 'package' keyword { res := gopls(t, tree, "rename", "a.go:1:3", "newname") res.checkExit(false) res.checkStderr("no identifier found") } // in 'package' identifier { res := gopls(t, tree, "rename", "a.go:1:9", "newname") res.checkExit(false) res.checkStderr(`cannot rename package: module path .* same as the package path, so .* no effect`) } // success, func oldname (and -diff) { res := gopls(t, tree, "rename", "-diff", "a.go:2:9", "newname") res.checkExit(true) res.checkStdout(regexp.QuoteMeta("-func oldname() {}")) res.checkStdout(regexp.QuoteMeta("+func newname() {}")) } } // TestSymbols tests the 'symbols' subcommand (../symbols.go). func TestSymbols(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func f() var v int const c = 0 `) // no files { res := gopls(t, tree, "symbols") res.checkExit(false) res.checkStderr("expects 1 argument") } // success { res := gopls(t, tree, "symbols", "a.go:123:456") // (line/col ignored) res.checkExit(true) res.checkStdout("f Function 2:6-2:7") res.checkStdout("v Variable 3:5-3:6") res.checkStdout("c Constant 4:7-4:8") } } // TestSemtok tests the 'semtok' subcommand (../semantictokens.go). func TestSemtok(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func f() var v int const c = 0 `) // no files { res := gopls(t, tree, "semtok") res.checkExit(false) res.checkStderr("expected one file name") } // success { res := gopls(t, tree, "semtok", "a.go") res.checkExit(true) got := res.stdout want := ` /*⇒7,keyword,[]*/package /*⇒1,namespace,[]*/a /*⇒4,keyword,[]*/func /*⇒1,function,[definition]*/f() /*⇒3,keyword,[]*/var /*⇒1,variable,[definition]*/v /*⇒3,type,[defaultLibrary]*/int /*⇒5,keyword,[]*/const /*⇒1,variable,[definition readonly]*/c = /*⇒1,number,[]*/0 `[1:] if got != want { t.Errorf("semtok: got <<%s>>, want <<%s>>", got, want) } } } func TestStats(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a -- b/b.go -- package b -- testdata/foo.go -- package foo `) // Trigger a bug report with a distinctive string // and check that it was durably recorded. oops := fmt.Sprintf("oops-%d", rand.Int()) { env := []string{"TEST_GOPLS_BUG=" + oops} res := goplsWithEnv(t, tree, env, "bug") res.checkExit(true) } res := gopls(t, tree, "stats") res.checkExit(true) var stats cmd.GoplsStats if err := json.Unmarshal([]byte(res.stdout), &stats); err != nil { t.Fatalf("failed to unmarshal JSON output of stats command: %v", err) } // a few sanity checks checks := []struct { field string got int want int }{ { "WorkspaceStats.Views[0].WorkspaceModules", stats.WorkspaceStats.Views[0].WorkspacePackages.Modules, 1, }, { "WorkspaceStats.Views[0].WorkspacePackages", stats.WorkspaceStats.Views[0].WorkspacePackages.Packages, 2, }, {"DirStats.Files", stats.DirStats.Files, 4}, {"DirStats.GoFiles", stats.DirStats.GoFiles, 2}, {"DirStats.ModFiles", stats.DirStats.ModFiles, 1}, {"DirStats.TestdataFiles", stats.DirStats.TestdataFiles, 1}, } for _, check := range checks { if check.got != check.want { t.Errorf("stats.%s = %d, want %d", check.field, check.got, check.want) } } // Check that we got a BugReport with the expected message. { got := fmt.Sprint(stats.BugReports) wants := []string{ "cmd/info.go", // File containing call to bug.Report oops, // Description } for _, want := range wants { if !strings.Contains(got, want) { t.Errorf("BugReports does not contain %q. Got:<<%s>>", want, got) break } } } // Check that -anon suppresses fields containing user information. { res2 := gopls(t, tree, "stats", "-anon") res2.checkExit(true) var stats2 cmd.GoplsStats if err := json.Unmarshal([]byte(res2.stdout), &stats2); err != nil { t.Fatalf("failed to unmarshal JSON output of stats command: %v", err) } if got := len(stats2.BugReports); got > 0 { t.Errorf("Got %d bug reports with -anon, want 0. Reports:%+v", got, stats2.BugReports) } var stats2AsMap map[string]any if err := json.Unmarshal([]byte(res2.stdout), &stats2AsMap); err != nil { t.Fatalf("failed to unmarshal JSON output of stats command: %v", err) } // GOPACKAGESDRIVER is user information, but is ok to print zero value. if v, ok := stats2AsMap["GOPACKAGESDRIVER"]; ok && v != "" { t.Errorf(`Got GOPACKAGESDRIVER=(%v, %v); want ("", true(found))`, v, ok) } } // Check that -anon suppresses fields containing non-zero user information. { res3 := goplsWithEnv(t, tree, []string{"GOPACKAGESDRIVER=off"}, "stats", "-anon") res3.checkExit(true) var statsAsMap3 map[string]interface{} if err := json.Unmarshal([]byte(res3.stdout), &statsAsMap3); err != nil { t.Fatalf("failed to unmarshal JSON output of stats command: %v", err) } // GOPACKAGESDRIVER is user information, want non-empty value to be omitted. if v, ok := statsAsMap3["GOPACKAGESDRIVER"]; ok { t.Errorf(`Got GOPACKAGESDRIVER=(%q, %v); want ("", false(not found))`, v, ok) } } } // TestCodeAction tests the 'codeaction' subcommand (../codeaction.go). func TestCodeAction(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a type T int func f() (int, string) { return } -- b.go -- package a import "io" var _ io.Reader = C{} type C struct{} `) // no arguments { res := gopls(t, tree, "codeaction") res.checkExit(false) res.checkStderr("expects at least 1 argument") } // list code actions in file { res := gopls(t, tree, "codeaction", "a.go") res.checkExit(true) res.checkStdout(`edit "Fill in return values" \[quickfix\]`) res.checkStdout(`command "Browse documentation for package a" \[source.doc\]`) } // list code actions in file, filtering by title { res := gopls(t, tree, "codeaction", "-title=Br.wse", "a.go") res.checkExit(true) got := res.stdout want := `command "Browse documentation for package a" [source.doc]` + "\n" if got != want { t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr) } } // list code actions at position (of io.Reader) { res := gopls(t, tree, "codeaction", "b.go:#31") res.checkExit(true) res.checkStdout(`command "Browse documentation for type io.Reader" \[source.doc]`) } // list quick fixes at position (of type T) { res := gopls(t, tree, "codeaction", "-kind=quickfix", "a.go:#15") res.checkExit(true) got := res.stdout want := `edit "Fill in return values" [quickfix]` + "\n" if got != want { t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr) } } // success, with explicit CodeAction kind and diagnostics span. { res := gopls(t, tree, "codeaction", "-kind=quickfix", "-exec", "b.go:#40") res.checkExit(true) got := res.stdout want := ` package a import "io" var _ io.Reader = C{} type C struct{} // Read implements io.Reader. func (c C) Read(p []byte) (n int, err error) { panic("unimplemented") } `[1:] if got != want { t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr) } } } // TestWorkspaceSymbol tests the 'workspace_symbol' subcommand (../workspace_symbol.go). func TestWorkspaceSymbol(t *testing.T) { t.Parallel() tree := writeTree(t, ` -- go.mod -- module example.com go 1.18 -- a.go -- package a func someFunctionName() `) // no files { res := gopls(t, tree, "workspace_symbol") res.checkExit(false) res.checkStderr("expects 1 argument") } // success { res := gopls(t, tree, "workspace_symbol", "meFun") res.checkExit(true) res.checkStdout("a.go:2:6-22 someFunctionName Function") } } // -- test framework -- func TestMain(m *testing.M) { switch os.Getenv("ENTRYPOINT") { case "goplsMain": goplsMain() default: os.Exit(m.Run()) } } // This function is a stand-in for gopls.main in ../../../../main.go. func goplsMain() { // Panic on bugs (unlike the production gopls command), // except in tests that inject calls to bug.Report. if os.Getenv("TEST_GOPLS_BUG") == "" { bug.PanicOnBugs = true } if v := os.Getenv("TEST_GOPLS_VERSION"); v != "" { version.VersionOverride = v } tool.Main(context.Background(), cmd.New(), os.Args[1:]) } // writeTree extracts a txtar archive into a new directory and returns its path. func writeTree(t *testing.T, archive string) string { root := t.TempDir() // This unfortunate step is required because gopls output // expands symbolic links in its input file names (arguably it // should not), and on macOS the temp dir is in /var -> private/var. root, err := filepath.EvalSymlinks(root) if err != nil { t.Fatal(err) } for _, f := range txtar.Parse([]byte(archive)).Files { filename := filepath.Join(root, f.Name) if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil { t.Fatal(err) } if err := os.WriteFile(filename, f.Data, 0666); err != nil { t.Fatal(err) } } return root } // gopls executes gopls in a child process. func gopls(t *testing.T, dir string, args ...string) *result { return goplsWithEnv(t, dir, nil, args...) } func goplsWithEnv(t *testing.T, dir string, env []string, args ...string) *result { testenv.NeedsTool(t, "go") // Catch inadvertent use of dir=".", which would make // the ReplaceAll below unpredictable. if !filepath.IsAbs(dir) { t.Fatalf("dir is not absolute: %s", dir) } goplsCmd := exec.Command(os.Args[0], args...) goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain") goplsCmd.Env = append(goplsCmd.Env, "GOPACKAGESDRIVER=off") goplsCmd.Env = append(goplsCmd.Env, env...) goplsCmd.Dir = dir goplsCmd.Stdout = new(bytes.Buffer) goplsCmd.Stderr = new(bytes.Buffer) cmdErr := goplsCmd.Run() stdout := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stdout), dir, ".") stderr := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stderr), dir, ".") exitcode := 0 if cmdErr != nil { if exitErr, ok := cmdErr.(*exec.ExitError); ok { exitcode = exitErr.ExitCode() } else { stderr = cmdErr.Error() // (execve failure) exitcode = -1 } } res := &result{ t: t, command: "gopls " + strings.Join(args, " "), exitcode: exitcode, stdout: stdout, stderr: stderr, } if false { t.Log(res) } return res } // A result holds the result of a gopls invocation, and provides assertion helpers. type result struct { t *testing.T command string exitcode int stdout, stderr string } func (res *result) String() string { return fmt.Sprintf("%s: exit=%d stdout=<<%s>> stderr=<<%s>>", res.command, res.exitcode, res.stdout, res.stderr) } // checkExit asserts that gopls returned the expected exit code. func (res *result) checkExit(success bool) { res.t.Helper() if (res.exitcode == 0) != success { res.t.Errorf("%s: exited with code %d, want success: %t (%s)", res.command, res.exitcode, success, res) } } // checkStdout asserts that the gopls standard output matches the pattern. func (res *result) checkStdout(pattern string) { res.t.Helper() res.checkOutput(pattern, "stdout", res.stdout) } // checkStderr asserts that the gopls standard error matches the pattern. func (res *result) checkStderr(pattern string) { res.t.Helper() res.checkOutput(pattern, "stderr", res.stderr) } func (res *result) checkOutput(pattern, name, content string) { res.t.Helper() if match, err := regexp.MatchString(pattern, content); err != nil { res.t.Errorf("invalid regexp: %v", err) } else if !match { res.t.Errorf("%s: %s does not match [%s]; got <<%s>>", res.command, name, pattern, content) } } // toJSON decodes res.stdout as JSON into to *ptr and reports its success. func (res *result) toJSON(ptr interface{}) bool { if err := json.Unmarshal([]byte(res.stdout), ptr); err != nil { res.t.Errorf("invalid JSON %v", err) return false } return true } // checkContent checks that the contents of the file are as expected. func checkContent(t *testing.T, filename, want string) { data, err := os.ReadFile(filename) if err != nil { t.Error(err) return } if got := string(data); got != want { t.Errorf("content of %s is <<%s>>, want <<%s>>", filename, got, want) } }
tools/gopls/internal/cmd/integration_test.go/0
{ "file_path": "tools/gopls/internal/cmd/integration_test.go", "repo_id": "tools", "token_count": 12083 }
735
report a bug in gopls Usage: gopls [flags] bug
tools/gopls/internal/cmd/usage/bug.hlp/0
{ "file_path": "tools/gopls/internal/cmd/usage/bug.hlp", "repo_id": "tools", "token_count": 21 }
736
list links in a file Usage: gopls [flags] links [links-flags] <filename> Example: list links contained within a file: $ gopls links internal/cmd/check.go links-flags: -json emit document links in JSON format
tools/gopls/internal/cmd/usage/links.hlp/0
{ "file_path": "tools/gopls/internal/cmd/usage/links.hlp", "repo_id": "tools", "token_count": 75 }
737
// 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 cmd import ( "context" "flag" "fmt" "strings" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/settings" "golang.org/x/tools/internal/tool" ) // workspaceSymbol implements the workspace_symbol verb for gopls. type workspaceSymbol struct { Matcher string `flag:"matcher" help:"specifies the type of matcher: fuzzy, fastfuzzy, casesensitive, or caseinsensitive.\nThe default is caseinsensitive."` app *Application } func (r *workspaceSymbol) Name() string { return "workspace_symbol" } func (r *workspaceSymbol) Parent() string { return r.app.Name() } func (r *workspaceSymbol) Usage() string { return "[workspace_symbol-flags] <query>" } func (r *workspaceSymbol) ShortHelp() string { return "search symbols in workspace" } func (r *workspaceSymbol) DetailedHelp(f *flag.FlagSet) { fmt.Fprint(f.Output(), ` Example: $ gopls workspace_symbol -matcher fuzzy 'wsymbols' workspace_symbol-flags: `) printFlagDefaults(f) } func (r *workspaceSymbol) Run(ctx context.Context, args ...string) error { if len(args) != 1 { return tool.CommandLineErrorf("workspace_symbol expects 1 argument") } opts := r.app.options r.app.options = func(o *settings.Options) { if opts != nil { opts(o) } switch strings.ToLower(r.Matcher) { case "fuzzy": o.SymbolMatcher = settings.SymbolFuzzy case "casesensitive": o.SymbolMatcher = settings.SymbolCaseSensitive case "fastfuzzy": o.SymbolMatcher = settings.SymbolFastFuzzy default: o.SymbolMatcher = settings.SymbolCaseInsensitive } } conn, err := r.app.connect(ctx) if err != nil { return err } defer conn.terminate(ctx) p := protocol.WorkspaceSymbolParams{ Query: args[0], } symbols, err := conn.Symbol(ctx, &p) if err != nil { return err } for _, s := range symbols { f, err := conn.openFile(ctx, s.Location.URI) if err != nil { return err } span, err := f.locationSpan(s.Location) if err != nil { return err } fmt.Printf("%s %s %s\n", span, s.Name, s.Kind) } return nil }
tools/gopls/internal/cmd/workspace_symbol.go/0
{ "file_path": "tools/gopls/internal/cmd/workspace_symbol.go", "repo_id": "tools", "token_count": 851 }
738
// 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 filecache_test // This file defines tests of the API of the filecache package. // // Some properties (e.g. garbage collection) cannot be exercised // through the API, so this test does not attempt to do so. import ( "bytes" cryptorand "crypto/rand" "fmt" "log" mathrand "math/rand" "os" "os/exec" "strconv" "strings" "testing" "golang.org/x/sync/errgroup" "golang.org/x/tools/gopls/internal/filecache" "golang.org/x/tools/internal/testenv" ) func TestBasics(t *testing.T) { const kind = "TestBasics" key := uniqueKey() // never used before value := []byte("hello") // Get of a never-seen key returns not found. if _, err := filecache.Get(kind, key); err != filecache.ErrNotFound { if strings.Contains(err.Error(), "operation not supported") || strings.Contains(err.Error(), "not implemented") { t.Skipf("skipping: %v", err) } t.Errorf("Get of random key returned err=%q, want not found", err) } // Set of a never-seen key and a small value succeeds. if err := filecache.Set(kind, key, value); err != nil { t.Errorf("Set failed: %v", err) } // Get of the key returns a copy of the value. if got, err := filecache.Get(kind, key); err != nil { t.Errorf("Get after Set failed: %v", err) } else if string(got) != string(value) { t.Errorf("Get after Set returned different value: got %q, want %q", got, value) } // The kind is effectively part of the key. if _, err := filecache.Get("different-kind", key); err != filecache.ErrNotFound { t.Errorf("Get with wrong kind returned err=%q, want not found", err) } } // TestConcurrency exercises concurrent access to the same entry. func TestConcurrency(t *testing.T) { if os.Getenv("GO_BUILDER_NAME") == "plan9-arm" { t.Skip(`skipping on plan9-arm builder due to golang/go#58748: failing with 'mount rpc error'`) } const kind = "TestConcurrency" key := uniqueKey() const N = 100 // concurrency level // Construct N distinct values, each larger // than a typical 4KB OS file buffer page. var values [N][8192]byte for i := range values { if _, err := mathrand.Read(values[i][:]); err != nil { t.Fatalf("rand: %v", err) } } // get calls Get and verifies that the cache entry // matches one of the values passed to Set. get := func(mustBeFound bool) error { got, err := filecache.Get(kind, key) if err != nil { if err == filecache.ErrNotFound && !mustBeFound { return nil // not found } return err } for _, want := range values { if bytes.Equal(want[:], got) { return nil // a match } } return fmt.Errorf("Get returned a value that was never Set") } // Perform N concurrent calls to Set and Get. // All sets must succeed. // All gets must return nothing, or one of the Set values; // there is no third possibility. var group errgroup.Group for i := range values { i := i group.Go(func() error { return filecache.Set(kind, key, values[i][:]) }) group.Go(func() error { return get(false) }) } if err := group.Wait(); err != nil { if strings.Contains(err.Error(), "operation not supported") || strings.Contains(err.Error(), "not implemented") { t.Skipf("skipping: %v", err) } t.Fatal(err) } // A final Get must report one of the values that was Set. if err := get(true); err != nil { t.Fatalf("final Get failed: %v", err) } } const ( testIPCKind = "TestIPC" testIPCValueA = "hello" testIPCValueB = "world" ) // TestIPC exercises interprocess communication through the cache. // It calls Set(A) in the parent, { Get(A); Set(B) } in the child // process, then Get(B) in the parent. func TestIPC(t *testing.T) { testenv.NeedsExec(t) keyA := uniqueKey() keyB := uniqueKey() value := []byte(testIPCValueA) // Set keyA. if err := filecache.Set(testIPCKind, keyA, value); err != nil { if strings.Contains(err.Error(), "operation not supported") { t.Skipf("skipping: %v", err) } t.Fatalf("Set: %v", err) } // Call ipcChild in a child process, // passing it the keys in the environment // (quoted, to avoid NUL termination of C strings). // It will Get(A) then Set(B). cmd := exec.Command(os.Args[0], os.Args[1:]...) cmd.Env = append(os.Environ(), "ENTRYPOINT=ipcChild", fmt.Sprintf("KEYA=%q", keyA), fmt.Sprintf("KEYB=%q", keyB)) cmd.Stdout = os.Stderr cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { t.Fatal(err) } // Verify keyB. got, err := filecache.Get(testIPCKind, keyB) if err != nil { t.Fatal(err) } if string(got) != "world" { t.Fatalf("Get(keyB) = %q, want %q", got, "world") } } // We define our own main function so that portions of // some tests can run in a separate (child) process. func TestMain(m *testing.M) { switch os.Getenv("ENTRYPOINT") { case "ipcChild": ipcChild() default: os.Exit(m.Run()) } } // ipcChild is the portion of TestIPC that runs in a child process. func ipcChild() { getenv := func(name string) (key [32]byte) { s, _ := strconv.Unquote(os.Getenv(name)) copy(key[:], []byte(s)) return } // Verify key A. got, err := filecache.Get(testIPCKind, getenv("KEYA")) if err != nil || string(got) != testIPCValueA { log.Fatalf("child: Get(key) = %q, %v; want %q", got, err, testIPCValueA) } // Set key B. if err := filecache.Set(testIPCKind, getenv("KEYB"), []byte(testIPCValueB)); err != nil { log.Fatalf("child: Set(keyB) failed: %v", err) } } // uniqueKey returns a key that has never been used before. func uniqueKey() (key [32]byte) { if _, err := cryptorand.Read(key[:]); err != nil { log.Fatalf("rand: %v", err) } return } func BenchmarkUncontendedGet(b *testing.B) { const kind = "BenchmarkUncontendedGet" key := uniqueKey() var value [8192]byte if _, err := mathrand.Read(value[:]); err != nil { b.Fatalf("rand: %v", err) } if err := filecache.Set(kind, key, value[:]); err != nil { b.Fatal(err) } b.ResetTimer() b.SetBytes(int64(len(value))) var group errgroup.Group group.SetLimit(50) for i := 0; i < b.N; i++ { group.Go(func() error { _, err := filecache.Get(kind, key) return err }) } if err := group.Wait(); err != nil { b.Fatal(err) } } // These two benchmarks are asymmetric: the one for Get imposes a // modest bound on concurrency (50) whereas the one for Set imposes a // much higher concurrency (1000) to test the implementation's // self-imposed bound. func BenchmarkUncontendedSet(b *testing.B) { const kind = "BenchmarkUncontendedSet" key := uniqueKey() var value [8192]byte const P = 1000 // parallelism b.SetBytes(P * int64(len(value))) for i := 0; i < b.N; i++ { // Perform P concurrent calls to Set. All must succeed. var group errgroup.Group for range [P]bool{} { group.Go(func() error { return filecache.Set(kind, key, value[:]) }) } if err := group.Wait(); err != nil { if strings.Contains(err.Error(), "operation not supported") || strings.Contains(err.Error(), "not implemented") { b.Skipf("skipping: %v", err) } b.Fatal(err) } } }
tools/gopls/internal/filecache/filecache_test.go/0
{ "file_path": "tools/gopls/internal/filecache/filecache_test.go", "repo_id": "tools", "token_count": 2710 }
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 ( "context" "go/ast" "go/types" ) // builtinArgKind determines the expected object kind for a builtin // argument. It attempts to use the AST hints from builtin.go where // possible. func (c *completer) builtinArgKind(ctx context.Context, obj types.Object, call *ast.CallExpr) objKind { builtin, err := c.snapshot.BuiltinFile(ctx) if err != nil { return 0 } exprIdx := exprAtPos(c.pos, call.Args) builtinObj := builtin.File.Scope.Lookup(obj.Name()) if builtinObj == nil { return 0 } decl, ok := builtinObj.Decl.(*ast.FuncDecl) if !ok || exprIdx >= len(decl.Type.Params.List) { return 0 } switch ptyp := decl.Type.Params.List[exprIdx].Type.(type) { case *ast.ChanType: return kindChan case *ast.ArrayType: return kindSlice case *ast.MapType: return kindMap case *ast.Ident: switch ptyp.Name { case "Type": switch obj.Name() { case "make": return kindChan | kindSlice | kindMap case "len": return kindSlice | kindMap | kindArray | kindString | kindChan case "cap": return kindSlice | kindArray | kindChan } } } return 0 } // builtinArgType infers the type of an argument to a builtin // function. parentInf is the inferred type info for the builtin // call's parent node. func (c *completer) builtinArgType(obj types.Object, call *ast.CallExpr, parentInf candidateInference) candidateInference { var ( exprIdx = exprAtPos(c.pos, call.Args) // Propagate certain properties from our parent's inference. inf = candidateInference{ typeName: parentInf.typeName, modifiers: parentInf.modifiers, } ) switch obj.Name() { case "append": if exprIdx <= 0 { // Infer first append() arg type as apparent return type of // append(). inf.objType = parentInf.objType if parentInf.variadic { inf.objType = types.NewSlice(inf.objType) } break } // For non-initial append() args, infer slice type from the first // append() arg, or from parent context. if len(call.Args) > 0 { inf.objType = c.pkg.TypesInfo().TypeOf(call.Args[0]) } if inf.objType == nil { inf.objType = parentInf.objType } if inf.objType == nil { break } inf.objType = deslice(inf.objType) // Check if we are completing the variadic append() param. inf.variadic = exprIdx == 1 && len(call.Args) <= 2 // Penalize the first append() argument as a candidate. You // don't normally append a slice to itself. if sliceChain := objChain(c.pkg.TypesInfo(), call.Args[0]); len(sliceChain) > 0 { inf.penalized = append(inf.penalized, penalizedObj{objChain: sliceChain, penalty: 0.9}) } case "delete": if exprIdx > 0 && len(call.Args) > 0 { // Try to fill in expected type of map key. firstArgType := c.pkg.TypesInfo().TypeOf(call.Args[0]) if firstArgType != nil { if mt, ok := firstArgType.Underlying().(*types.Map); ok { inf.objType = mt.Key() } } } case "copy": var t1, t2 types.Type if len(call.Args) > 0 { t1 = c.pkg.TypesInfo().TypeOf(call.Args[0]) if len(call.Args) > 1 { t2 = c.pkg.TypesInfo().TypeOf(call.Args[1]) } } // Fill in expected type of either arg if the other is already present. if exprIdx == 1 && t1 != nil { inf.objType = t1 } else if exprIdx == 0 && t2 != nil { inf.objType = t2 } case "new": inf.typeName.wantTypeName = true if parentInf.objType != nil { // Expected type for "new" is the de-pointered parent type. if ptr, ok := parentInf.objType.Underlying().(*types.Pointer); ok { inf.objType = ptr.Elem() } } case "make": if exprIdx == 0 { inf.typeName.wantTypeName = true inf.objType = parentInf.objType } else { inf.objType = types.Typ[types.UntypedInt] } } return inf }
tools/gopls/internal/golang/completion/builtin.go/0
{ "file_path": "tools/gopls/internal/golang/completion/builtin.go", "repo_id": "tools", "token_count": 1506 }
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 snippet implements the specification for the LSP snippet format. // // Snippets are "tab stop" templates returned as an optional attribute of LSP // completion candidates. As the user presses tab, they cycle through a series of // tab stops defined in the snippet. Each tab stop can optionally have placeholder // text, which can be pre-selected by editors. For a full description of syntax // and features, see "Snippet Syntax" at // https://microsoft.github.io/language-server-protocol/specifications/specification-3-14/#textDocument_completion. // // A typical snippet looks like "foo(${1:i int}, ${2:s string})". package snippet import ( "fmt" "strings" ) // A Builder is used to build an LSP snippet piecemeal. // The zero value is ready to use. Do not copy a non-zero Builder. type Builder struct { // currentTabStop is the index of the previous tab stop. The // next tab stop will be currentTabStop+1. currentTabStop int sb strings.Builder } // Escape characters defined in https://microsoft.github.io/language-server-protocol/specifications/specification-3-14/#textDocument_completion under "Grammar". var replacer = strings.NewReplacer( `\`, `\\`, `}`, `\}`, `$`, `\$`, ) func (b *Builder) WriteText(s string) { replacer.WriteString(&b.sb, s) } func (b *Builder) PrependText(s string) { rawSnip := b.String() b.sb.Reset() b.WriteText(s) b.sb.WriteString(rawSnip) } func (b *Builder) Write(data []byte) (int, error) { return b.sb.Write(data) } // WritePlaceholder writes a tab stop and placeholder value to the Builder. // The callback style allows for creating nested placeholders. To write an // empty tab stop, provide a nil callback. func (b *Builder) WritePlaceholder(fn func(*Builder)) { fmt.Fprintf(&b.sb, "${%d:", b.nextTabStop()) if fn != nil { fn(b) } b.sb.WriteByte('}') } // WriteFinalTabstop marks where cursor ends up after the user has // cycled through all the normal tab stops. It defaults to the // character after the snippet. func (b *Builder) WriteFinalTabstop() { fmt.Fprint(&b.sb, "$0") } // In addition to '\', '}', and '$', snippet choices also use '|' and ',' as // meta characters, so they must be escaped within the choices. var choiceReplacer = strings.NewReplacer( `\`, `\\`, `}`, `\}`, `$`, `\$`, `|`, `\|`, `,`, `\,`, ) // WriteChoice writes a tab stop and list of text choices to the Builder. // The user's editor will prompt the user to choose one of the choices. func (b *Builder) WriteChoice(choices []string) { fmt.Fprintf(&b.sb, "${%d|", b.nextTabStop()) for i, c := range choices { if i != 0 { b.sb.WriteByte(',') } choiceReplacer.WriteString(&b.sb, c) } b.sb.WriteString("|}") } // String returns the built snippet string. func (b *Builder) String() string { return b.sb.String() } // Clone returns a copy of b. func (b *Builder) Clone() *Builder { var clone Builder clone.sb.WriteString(b.String()) return &clone } // nextTabStop returns the next tab stop index for a new placeholder. func (b *Builder) nextTabStop() int { // Tab stops start from 1, so increment before returning. b.currentTabStop++ return b.currentTabStop }
tools/gopls/internal/golang/completion/snippet/snippet_builder.go/0
{ "file_path": "tools/gopls/internal/golang/completion/snippet/snippet_builder.go", "repo_id": "tools", "token_count": 1085 }
741
// 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 golang import ( "bytes" "context" "encoding/json" "fmt" "os" "path/filepath" "strings" "golang.org/x/tools/gopls/internal/cache" "golang.org/x/tools/gopls/internal/cache/metadata" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/settings" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/gocommand" ) // GCOptimizationDetails invokes the Go compiler on the specified // package and reports its log of optimizations decisions as a set of // diagnostics. // // TODO(adonovan): this feature needs more consistent and informative naming. // Now that the compiler is cmd/compile, "GC" now means only "garbage collection". // I propose "(Toggle|Display) Go compiler optimization details" in the UI, // and CompilerOptimizationDetails for this function and compileropts.go for the file. func GCOptimizationDetails(ctx context.Context, snapshot *cache.Snapshot, mp *metadata.Package) (map[protocol.DocumentURI][]*cache.Diagnostic, error) { if len(mp.CompiledGoFiles) == 0 { return nil, nil } pkgDir := filepath.Dir(mp.CompiledGoFiles[0].Path()) outDir, err := os.MkdirTemp("", fmt.Sprintf("gopls-%d.details", os.Getpid())) if err != nil { return nil, err } defer func() { if err := os.RemoveAll(outDir); err != nil { event.Error(ctx, "cleaning gcdetails dir", err) } }() tmpFile, err := os.CreateTemp(os.TempDir(), "gopls-x") if err != nil { return nil, err } tmpFile.Close() // ignore error defer os.Remove(tmpFile.Name()) outDirURI := protocol.URIFromPath(outDir) // GC details doesn't handle Windows URIs in the form of "file:///C:/...", // so rewrite them to "file://C:/...". See golang/go#41614. if !strings.HasPrefix(outDir, "/") { outDirURI = protocol.DocumentURI(strings.Replace(string(outDirURI), "file:///", "file://", 1)) } inv, cleanupInvocation, err := snapshot.GoCommandInvocation(false, &gocommand.Invocation{ Verb: "build", Args: []string{ fmt.Sprintf("-gcflags=-json=0,%s", outDirURI), fmt.Sprintf("-o=%s", tmpFile.Name()), ".", }, WorkingDir: pkgDir, }) if err != nil { return nil, err } defer cleanupInvocation() _, err = snapshot.View().GoCommandRunner().Run(ctx, *inv) if err != nil { return nil, err } files, err := findJSONFiles(outDir) if err != nil { return nil, err } reports := make(map[protocol.DocumentURI][]*cache.Diagnostic) opts := snapshot.Options() var parseError error for _, fn := range files { uri, diagnostics, err := parseDetailsFile(fn, opts) if err != nil { // expect errors for all the files, save 1 parseError = err } fh := snapshot.FindFile(uri) if fh == nil { continue } if pkgDir != filepath.Dir(fh.URI().Path()) { // https://github.com/golang/go/issues/42198 // sometimes the detail diagnostics generated for files // outside the package can never be taken back. continue } reports[fh.URI()] = diagnostics } return reports, parseError } func parseDetailsFile(filename string, options *settings.Options) (protocol.DocumentURI, []*cache.Diagnostic, error) { buf, err := os.ReadFile(filename) if err != nil { return "", nil, err } var ( uri protocol.DocumentURI i int diagnostics []*cache.Diagnostic ) type metadata struct { File string `json:"file,omitempty"` } for dec := json.NewDecoder(bytes.NewReader(buf)); dec.More(); { // The first element always contains metadata. if i == 0 { i++ m := new(metadata) if err := dec.Decode(m); err != nil { return "", nil, err } if !strings.HasSuffix(m.File, ".go") { continue // <autogenerated> } uri = protocol.URIFromPath(m.File) continue } d := new(protocol.Diagnostic) if err := dec.Decode(d); err != nil { return "", nil, err } d.Tags = []protocol.DiagnosticTag{} // must be an actual slice msg := d.Code.(string) if msg != "" { msg = fmt.Sprintf("%s(%s)", msg, d.Message) } if !showDiagnostic(msg, d.Source, options) { continue } var related []protocol.DiagnosticRelatedInformation for _, ri := range d.RelatedInformation { // TODO(rfindley): The compiler uses LSP-like JSON to encode gc details, // however the positions it uses are 1-based UTF-8: // https://github.com/golang/go/blob/master/src/cmd/compile/internal/logopt/log_opts.go // // Here, we adjust for 0-based positions, but do not translate UTF-8 to UTF-16. related = append(related, protocol.DiagnosticRelatedInformation{ Location: protocol.Location{ URI: ri.Location.URI, Range: zeroIndexedRange(ri.Location.Range), }, Message: ri.Message, }) } diagnostic := &cache.Diagnostic{ URI: uri, Range: zeroIndexedRange(d.Range), Message: msg, Severity: d.Severity, Source: cache.OptimizationDetailsError, // d.Source is always "go compiler" as of 1.16, use our own Tags: d.Tags, Related: related, } diagnostics = append(diagnostics, diagnostic) i++ } return uri, diagnostics, nil } // showDiagnostic reports whether a given diagnostic should be shown to the end // user, given the current options. func showDiagnostic(msg, source string, o *settings.Options) bool { if source != "go compiler" { return false } if o.Annotations == nil { return true } switch { case strings.HasPrefix(msg, "canInline") || strings.HasPrefix(msg, "cannotInline") || strings.HasPrefix(msg, "inlineCall"): return o.Annotations[settings.Inline] case strings.HasPrefix(msg, "escape") || msg == "leak": return o.Annotations[settings.Escape] case strings.HasPrefix(msg, "nilcheck"): return o.Annotations[settings.Nil] case strings.HasPrefix(msg, "isInBounds") || strings.HasPrefix(msg, "isSliceInBounds"): return o.Annotations[settings.Bounds] } return false } // The range produced by the compiler is 1-indexed, so subtract range by 1. func zeroIndexedRange(rng protocol.Range) protocol.Range { return protocol.Range{ Start: protocol.Position{ Line: rng.Start.Line - 1, Character: rng.Start.Character - 1, }, End: protocol.Position{ Line: rng.End.Line - 1, Character: rng.End.Character - 1, }, } } func findJSONFiles(dir string) ([]string, error) { ans := []string{} f := func(path string, fi os.FileInfo, _ error) error { if fi.IsDir() { return nil } if strings.HasSuffix(path, ".json") { ans = append(ans, path) } return nil } err := filepath.Walk(dir, f) return ans, err }
tools/gopls/internal/golang/gc_annotations.go/0
{ "file_path": "tools/gopls/internal/golang/gc_annotations.go", "repo_id": "tools", "token_count": 2546 }
742
// 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 // TODO(adonovan): // // - method of generic concrete type -> arbitrary instances of same // // - make satisfy work across packages. // // - tests, tests, tests: // - play with renamings in the k8s tree. // - generics // - error cases (e.g. conflicts) // - renaming a symbol declared in the module cache // (currently proceeds with half of the renaming!) // - make sure all tests have both a local and a cross-package analogue. // - look at coverage // - special cases: embedded fields, interfaces, test variants, // function-local things with uppercase names; // packages with type errors (currently 'satisfy' rejects them), // package with missing imports; // // - measure performance in k8s. // // - The original gorename tool assumed well-typedness, but the gopls feature // does no such check (which actually makes it much more useful). // Audit to ensure it is safe on ill-typed code. // // - Generics support was no doubt buggy before but incrementalization // may have exacerbated it. If the problem were just about objects, // defs and uses it would be fairly simple, but type assignability // comes into play in the 'satisfy' check for method renamings. // De-instantiating Vector[int] to Vector[T] changes its type. // We need to come up with a theory for the satisfy check that // works with generics, and across packages. We currently have no // simple way to pass types between packages (think: objectpath for // types), though presumably exportdata could be pressed into service. // // - FileID-based de-duplication of edits to different URIs for the same file. import ( "context" "errors" "fmt" "go/ast" "go/token" "go/types" "path" "path/filepath" "regexp" "sort" "strconv" "strings" "golang.org/x/mod/modfile" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/types/objectpath" "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/util/bug" "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/aliases" "golang.org/x/tools/internal/diff" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/refactor/satisfy" ) // A renamer holds state of a single call to renameObj, which renames // an object (or several coupled objects) within a single type-checked // syntax package. type renamer struct { pkg *cache.Package // the syntax package in which the renaming is applied objsToUpdate map[types.Object]bool // records progress of calls to check conflicts []string from, to string satisfyConstraints map[satisfy.Constraint]bool msets typeutil.MethodSetCache changeMethods bool } // A PrepareItem holds the result of a "prepare rename" operation: // the source range and value of a selected identifier. type PrepareItem struct { Range protocol.Range Text string } // PrepareRename searches for a valid renaming at position pp. // // The returned usererr is intended to be displayed to the user to explain why // the prepare fails. Probably we could eliminate the redundancy in returning // two errors, but for now this is done defensively. func PrepareRename(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, pp protocol.Position) (_ *PrepareItem, usererr, err error) { ctx, done := event.Start(ctx, "golang.PrepareRename") defer done() // Is the cursor within the package name declaration? if pgf, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, pp); err != nil { return nil, err, err } else if inPackageName { item, err := prepareRenamePackageName(ctx, snapshot, pgf) return item, err, err } // Ordinary (non-package) renaming. // // Type-check the current package, locate the reference at the position, // validate the object, and report its name and range. // // TODO(adonovan): in all cases below, we return usererr=nil, // which means we return (nil, nil) at the protocol // layer. This seems like a bug, or at best an exploitation of // knowledge of VSCode-specific behavior. Can we avoid that? pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, f.URI()) if err != nil { return nil, nil, err } pos, err := pgf.PositionPos(pp) if err != nil { return nil, nil, err } targets, node, err := objectsAt(pkg.TypesInfo(), pgf.File, pos) if err != nil { return nil, nil, err } var obj types.Object for obj = range targets { break // pick one arbitrarily } if err := checkRenamable(obj); err != nil { return nil, nil, err } rng, err := pgf.NodeRange(node) if err != nil { return nil, nil, err } if _, isImport := node.(*ast.ImportSpec); isImport { // We're not really renaming the import path. rng.End = rng.Start } return &PrepareItem{ Range: rng, Text: obj.Name(), }, nil, nil } func prepareRenamePackageName(ctx context.Context, snapshot *cache.Snapshot, pgf *parsego.File) (*PrepareItem, error) { // Does the client support file renaming? fileRenameSupported := false for _, op := range snapshot.Options().SupportedResourceOperations { if op == protocol.Rename { fileRenameSupported = true break } } if !fileRenameSupported { return nil, errors.New("can't rename package: LSP client does not support file renaming") } // Check validity of the metadata for the file's containing package. meta, err := NarrowestMetadataForFile(ctx, snapshot, pgf.URI) if err != nil { return nil, err } if meta.Name == "main" { return nil, fmt.Errorf("can't rename package \"main\"") } if strings.HasSuffix(string(meta.Name), "_test") { return nil, fmt.Errorf("can't rename x_test packages") } if meta.Module == nil { return nil, fmt.Errorf("can't rename package: missing module information for package %q", meta.PkgPath) } if meta.Module.Path == string(meta.PkgPath) { return nil, fmt.Errorf("can't rename package: package path %q is the same as module path %q", meta.PkgPath, meta.Module.Path) } // Return the location of the package declaration. rng, err := pgf.NodeRange(pgf.File.Name) if err != nil { return nil, err } return &PrepareItem{ Range: rng, Text: string(meta.Name), }, nil } func checkRenamable(obj types.Object) error { switch obj := obj.(type) { case *types.Var: if obj.Embedded() { return fmt.Errorf("can't rename embedded fields: rename the type directly or name the field") } case *types.Builtin, *types.Nil: return fmt.Errorf("%s is built in and cannot be renamed", obj.Name()) } if obj.Pkg() == nil || obj.Pkg().Path() == "unsafe" { // e.g. error.Error, unsafe.Pointer return fmt.Errorf("%s is built in and cannot be renamed", obj.Name()) } if obj.Name() == "_" { return errors.New("can't rename \"_\"") } return nil } // Rename returns a map of TextEdits for each file modified when renaming a // given identifier within a package and a boolean value of true for renaming // package and false otherwise. func Rename(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, pp protocol.Position, newName string) (map[protocol.DocumentURI][]protocol.TextEdit, bool, error) { ctx, done := event.Start(ctx, "golang.Rename") defer done() if !isValidIdentifier(newName) { return nil, false, fmt.Errorf("invalid identifier to rename: %q", newName) } // Cursor within package name declaration? _, inPackageName, err := parsePackageNameDecl(ctx, snapshot, f, pp) if err != nil { return nil, false, err } var editMap map[protocol.DocumentURI][]diff.Edit if inPackageName { editMap, err = renamePackageName(ctx, snapshot, f, PackageName(newName)) } else { editMap, err = renameOrdinary(ctx, snapshot, f, pp, newName) } if err != nil { return nil, false, err } // Convert edits to protocol form. result := make(map[protocol.DocumentURI][]protocol.TextEdit) for uri, edits := range editMap { // Sort and de-duplicate edits. // // Overlapping edits may arise in local renamings (due // to type switch implicits) and globals ones (due to // processing multiple package variants). // // We assume renaming produces diffs that are all // replacements (no adjacent insertions that might // become reordered) and that are either identical or // non-overlapping. diff.SortEdits(edits) filtered := edits[:0] for i, edit := range edits { if i == 0 || edit != filtered[len(filtered)-1] { filtered = append(filtered, edit) } } edits = filtered // TODO(adonovan): the logic above handles repeat edits to the // same file URI (e.g. as a member of package p and p_test) but // is not sufficient to handle file-system level aliasing arising // from symbolic or hard links. For that, we should use a // robustio-FileID-keyed map. // See https://go.dev/cl/457615 for example. // This really occurs in practice, e.g. kubernetes has // vendor/k8s.io/kubectl -> ../../staging/src/k8s.io/kubectl. fh, err := snapshot.ReadFile(ctx, uri) if err != nil { return nil, false, err } data, err := fh.Content() if err != nil { return nil, false, err } m := protocol.NewMapper(uri, data) textedits, err := protocol.EditsFromDiffEdits(m, edits) if err != nil { return nil, false, err } result[uri] = textedits } return result, inPackageName, nil } // renameOrdinary renames an ordinary (non-package) name throughout the workspace. func renameOrdinary(ctx context.Context, snapshot *cache.Snapshot, f file.Handle, pp protocol.Position, newName string) (map[protocol.DocumentURI][]diff.Edit, error) { // Type-check the referring package and locate the object(s). // // Unlike NarrowestPackageForFile, this operation prefers the // widest variant as, for non-exported identifiers, it is the // only package we need. (In case you're wondering why // 'references' doesn't also want the widest variant: it // computes the union across all variants.) var targets map[types.Object]ast.Node var pkg *cache.Package { mps, err := snapshot.MetadataForFile(ctx, f.URI()) if err != nil { return nil, err } metadata.RemoveIntermediateTestVariants(&mps) if len(mps) == 0 { return nil, fmt.Errorf("no package metadata for file %s", f.URI()) } widest := mps[len(mps)-1] // widest variant may include _test.go files pkgs, err := snapshot.TypeCheck(ctx, widest.ID) if err != nil { return nil, err } pkg = pkgs[0] pgf, err := pkg.File(f.URI()) if err != nil { return nil, err // "can't happen" } pos, err := pgf.PositionPos(pp) if err != nil { return nil, err } objects, _, err := objectsAt(pkg.TypesInfo(), pgf.File, pos) if err != nil { return nil, err } targets = objects } // Pick a representative object arbitrarily. // (All share the same name, pos, and kind.) var obj types.Object for obj = range targets { break } if obj.Name() == newName { return nil, fmt.Errorf("old and new names are the same: %s", newName) } if err := checkRenamable(obj); err != nil { return nil, err } // Find objectpath, if object is exported ("" otherwise). var declObjPath objectpath.Path if obj.Exported() { // objectpath.For requires the origin of a generic function or type, not an // instantiation (a bug?). // // Note that unlike Funcs, TypeNames are always canonical (they are "left" // of the type parameters, unlike methods). switch obj.(type) { // avoid "obj :=" since cases reassign the var case *types.TypeName: if _, ok := aliases.Unalias(obj.Type()).(*types.TypeParam); ok { // As with capitalized function parameters below, type parameters are // local. goto skipObjectPath } case *types.Func: obj = obj.(*types.Func).Origin() case *types.Var: // TODO(adonovan): do vars need the origin treatment too? (issue #58462) // Function parameter and result vars that are (unusually) // capitalized are technically exported, even though they // cannot be referenced, because they may affect downstream // error messages. But we can safely treat them as local. // // This is not merely an optimization: the renameExported // operation gets confused by such vars. It finds them from // objectpath, the classifies them as local vars, but as // they came from export data they lack syntax and the // correct scope tree (issue #61294). if !obj.(*types.Var).IsField() && !isPackageLevel(obj) { goto skipObjectPath } } if path, err := objectpath.For(obj); err == nil { declObjPath = path } skipObjectPath: } // Nonexported? Search locally. if declObjPath == "" { var objects []types.Object for obj := range targets { objects = append(objects, obj) } editMap, _, err := renameObjects(newName, pkg, objects...) return editMap, err } // Exported: search globally. // // For exported package-level var/const/func/type objects, the // search scope is just the direct importers. // // For exported fields and methods, the scope is the // transitive rdeps. (The exportedness of the field's struct // or method's receiver is irrelevant.) transitive := false switch obj := obj.(type) { case *types.TypeName: // Renaming an exported package-level type // requires us to inspect all transitive rdeps // in the event that the type is embedded. // // TODO(adonovan): opt: this is conservative // but inefficient. Instead, expand the scope // of the search only if we actually encounter // an embedding of the type, and only then to // the rdeps of the embedding package. if obj.Parent() == obj.Pkg().Scope() { transitive = true } case *types.Var: if obj.IsField() { transitive = true // field } // TODO(adonovan): opt: process only packages that // contain a reference (xrefs) to the target field. case *types.Func: if obj.Type().(*types.Signature).Recv() != nil { transitive = true // method } // It's tempting to optimize by skipping // packages that don't contain a reference to // the method in the xrefs index, but we still // need to apply the satisfy check to those // packages to find assignment statements that // might expands the scope of the renaming. } // Type-check all the packages to inspect. declURI := protocol.URIFromPath(pkg.FileSet().File(obj.Pos()).Name()) pkgs, err := typeCheckReverseDependencies(ctx, snapshot, declURI, transitive) if err != nil { return nil, err } // Apply the renaming to the (initial) object. declPkgPath := PackagePath(obj.Pkg().Path()) return renameExported(pkgs, declPkgPath, declObjPath, newName) } // typeCheckReverseDependencies returns the type-checked packages for // the reverse dependencies of all packages variants containing // file declURI. The packages are in some topological order. // // It includes all variants (even intermediate test variants) for the // purposes of computing reverse dependencies, but discards ITVs for // the actual renaming work. // // (This neglects obscure edge cases where a _test.go file changes the // selectors used only in an ITV, but life is short. Also sin must be // punished.) func typeCheckReverseDependencies(ctx context.Context, snapshot *cache.Snapshot, declURI protocol.DocumentURI, transitive bool) ([]*cache.Package, error) { variants, err := snapshot.MetadataForFile(ctx, declURI) if err != nil { return nil, err } // variants must include ITVs for the reverse dependency // computation, but they are filtered out before we typecheck. allRdeps := make(map[PackageID]*metadata.Package) for _, variant := range variants { rdeps, err := snapshot.ReverseDependencies(ctx, variant.ID, transitive) if err != nil { return nil, err } allRdeps[variant.ID] = variant // include self for id, meta := range rdeps { allRdeps[id] = meta } } var ids []PackageID for id, meta := range allRdeps { if meta.IsIntermediateTestVariant() { continue } ids = append(ids, id) } // Sort the packages into some topological order of the // (unfiltered) metadata graph. metadata.SortPostOrder(snapshot, ids) // Dependencies must be visited first since they can expand // the search set. Ideally we would process the (filtered) set // of packages in the parallel postorder of the snapshot's // (unfiltered) metadata graph, but this is quite tricky // without a good graph abstraction. // // For now, we visit packages sequentially in order of // ascending height, like an inverted breadth-first search. // // Type checking is by far the dominant cost, so // overlapping it with renaming may not be worthwhile. return snapshot.TypeCheck(ctx, ids...) } // renameExported renames the object denoted by (pkgPath, objPath) // within the specified packages, along with any other objects that // must be renamed as a consequence. The slice of packages must be // topologically ordered. func renameExported(pkgs []*cache.Package, declPkgPath PackagePath, declObjPath objectpath.Path, newName string) (map[protocol.DocumentURI][]diff.Edit, error) { // A target is a name for an object that is stable across types.Packages. type target struct { pkg PackagePath obj objectpath.Path } // Populate the initial set of target objects. // This set may grow as we discover the consequences of each renaming. // // TODO(adonovan): strictly, each cone of reverse dependencies // of a single variant should have its own target map that // monotonically expands as we go up the import graph, because // declarations in test files can alter the set of // package-level names and change the meaning of field and // method selectors. So if we parallelize the graph // visitation (see above), we should also compute the targets // as a union of dependencies. // // Or we could decide that the logic below is fast enough not // to need parallelism. In small measurements so far the // type-checking step is about 95% and the renaming only 5%. targets := map[target]bool{{declPkgPath, declObjPath}: true} // Apply the renaming operation to each package. allEdits := make(map[protocol.DocumentURI][]diff.Edit) for _, pkg := range pkgs { // Resolved target objects within package pkg. var objects []types.Object for t := range targets { p := pkg.DependencyTypes(t.pkg) if p == nil { continue // indirect dependency of no consequence } obj, err := objectpath.Object(p, t.obj) if err != nil { // Possibly a method or an unexported type // that is not reachable through export data? // See https://github.com/golang/go/issues/60789. // // TODO(adonovan): it seems unsatisfactory that Object // should return an error for a "valid" path. Perhaps // we should define such paths as invalid and make // objectpath.For compute reachability? // Would that be a compatible change? continue } objects = append(objects, obj) } if len(objects) == 0 { continue // no targets of consequence to this package } // Apply the renaming. editMap, moreObjects, err := renameObjects(newName, pkg, objects...) if err != nil { return nil, err } // It is safe to concatenate the edits as they are non-overlapping // (or identical, in which case they will be de-duped by Rename). for uri, edits := range editMap { allEdits[uri] = append(allEdits[uri], edits...) } // Expand the search set? for obj := range moreObjects { objpath, err := objectpath.For(obj) if err != nil { continue // not exported } target := target{PackagePath(obj.Pkg().Path()), objpath} targets[target] = true // TODO(adonovan): methods requires dynamic // programming of the product targets x // packages as any package might add a new // target (from a forward dep) as a // consequence, and any target might imply a // new set of rdeps. See golang/go#58461. } } return allEdits, nil } // renamePackageName renames package declarations, imports, and go.mod files. func renamePackageName(ctx context.Context, s *cache.Snapshot, f file.Handle, newName PackageName) (map[protocol.DocumentURI][]diff.Edit, error) { // Rename the package decl and all imports. renamingEdits, err := renamePackage(ctx, s, f, newName) if err != nil { return nil, err } // Update the last component of the file's enclosing directory. oldBase := filepath.Dir(f.URI().Path()) newPkgDir := filepath.Join(filepath.Dir(oldBase), string(newName)) // Update any affected replace directives in go.mod files. // TODO(adonovan): extract into its own function. // // Get all workspace modules. // TODO(adonovan): should this operate on all go.mod files, // irrespective of whether they are included in the workspace? modFiles := s.View().ModFiles() for _, m := range modFiles { fh, err := s.ReadFile(ctx, m) if err != nil { return nil, err } pm, err := s.ParseMod(ctx, fh) if err != nil { return nil, err } modFileDir := filepath.Dir(pm.URI.Path()) affectedReplaces := []*modfile.Replace{} // Check if any replace directives need to be fixed for _, r := range pm.File.Replace { if !strings.HasPrefix(r.New.Path, "/") && !strings.HasPrefix(r.New.Path, "./") && !strings.HasPrefix(r.New.Path, "../") { continue } replacedPath := r.New.Path if strings.HasPrefix(r.New.Path, "./") || strings.HasPrefix(r.New.Path, "../") { replacedPath = filepath.Join(modFileDir, r.New.Path) } // TODO: Is there a risk of converting a '\' delimited replacement to a '/' delimited replacement? if !strings.HasPrefix(filepath.ToSlash(replacedPath)+"/", filepath.ToSlash(oldBase)+"/") { continue // not affected by the package renaming } affectedReplaces = append(affectedReplaces, r) } if len(affectedReplaces) == 0 { continue } copied, err := modfile.Parse("", pm.Mapper.Content, nil) if err != nil { return nil, err } for _, r := range affectedReplaces { replacedPath := r.New.Path if strings.HasPrefix(r.New.Path, "./") || strings.HasPrefix(r.New.Path, "../") { replacedPath = filepath.Join(modFileDir, r.New.Path) } suffix := strings.TrimPrefix(replacedPath, oldBase) newReplacedPath, err := filepath.Rel(modFileDir, newPkgDir+suffix) if err != nil { return nil, err } newReplacedPath = filepath.ToSlash(newReplacedPath) if !strings.HasPrefix(newReplacedPath, "/") && !strings.HasPrefix(newReplacedPath, "../") { newReplacedPath = "./" + newReplacedPath } if err := copied.AddReplace(r.Old.Path, "", newReplacedPath, ""); err != nil { return nil, err } } copied.Cleanup() newContent, err := copied.Format() if err != nil { return nil, err } // Calculate the edits to be made due to the change. edits := diff.Bytes(pm.Mapper.Content, newContent) renamingEdits[pm.URI] = append(renamingEdits[pm.URI], edits...) } return renamingEdits, nil } // renamePackage computes all workspace edits required to rename the package // described by the given metadata, to newName, by renaming its package // directory. // // It updates package clauses and import paths for the renamed package as well // as any other packages affected by the directory renaming among all packages // known to the snapshot. func renamePackage(ctx context.Context, s *cache.Snapshot, f file.Handle, newName PackageName) (map[protocol.DocumentURI][]diff.Edit, error) { if strings.HasSuffix(string(newName), "_test") { return nil, fmt.Errorf("cannot rename to _test package") } // We need metadata for the relevant package and module paths. // These should be the same for all packages containing the file. meta, err := NarrowestMetadataForFile(ctx, s, f.URI()) if err != nil { return nil, err } oldPkgPath := meta.PkgPath if meta.Module == nil { return nil, fmt.Errorf("cannot rename package: missing module information for package %q", meta.PkgPath) } modulePath := PackagePath(meta.Module.Path) if modulePath == oldPkgPath { return nil, fmt.Errorf("cannot rename package: module path %q is the same as the package path, so renaming the package directory would have no effect", modulePath) } newPathPrefix := path.Join(path.Dir(string(oldPkgPath)), string(newName)) // We must inspect all packages, not just direct importers, // because we also rename subpackages, which may be unrelated. // (If the renamed package imports a subpackage it may require // edits to both its package and import decls.) allMetadata, err := s.AllMetadata(ctx) if err != nil { return nil, err } // Rename package and import declarations in all relevant packages. edits := make(map[protocol.DocumentURI][]diff.Edit) for _, mp := range allMetadata { // Special case: x_test packages for the renamed package will not have the // package path as a dir prefix, but still need their package clauses // renamed. if mp.PkgPath == oldPkgPath+"_test" { if err := renamePackageClause(ctx, mp, s, newName+"_test", edits); err != nil { return nil, err } continue } // Subtle: check this condition before checking for valid module info // below, because we should not fail this operation if unrelated packages // lack module info. if !strings.HasPrefix(string(mp.PkgPath)+"/", string(oldPkgPath)+"/") { continue // not affected by the package renaming } if mp.Module == nil { // This check will always fail under Bazel. return nil, fmt.Errorf("cannot rename package: missing module information for package %q", mp.PkgPath) } if modulePath != PackagePath(mp.Module.Path) { continue // don't edit imports if nested package and renaming package have different module paths } // Renaming a package consists of changing its import path and package name. suffix := strings.TrimPrefix(string(mp.PkgPath), string(oldPkgPath)) newPath := newPathPrefix + suffix pkgName := mp.Name if mp.PkgPath == oldPkgPath { pkgName = newName if err := renamePackageClause(ctx, mp, s, newName, edits); err != nil { return nil, err } } imp := ImportPath(newPath) // TODO(adonovan): what if newPath has vendor/ prefix? if err := renameImports(ctx, s, mp, imp, pkgName, edits); err != nil { return nil, err } } return edits, nil } // renamePackageClause computes edits renaming the package clause of files in // the package described by the given metadata, to newName. // // Edits are written into the edits map. func renamePackageClause(ctx context.Context, mp *metadata.Package, snapshot *cache.Snapshot, newName PackageName, edits map[protocol.DocumentURI][]diff.Edit) error { // Rename internal references to the package in the renaming package. for _, uri := range mp.CompiledGoFiles { fh, err := snapshot.ReadFile(ctx, uri) if err != nil { return err } f, err := snapshot.ParseGo(ctx, fh, parsego.Header) if err != nil { return err } if f.File.Name == nil { continue // no package declaration } edit, err := posEdit(f.Tok, f.File.Name.Pos(), f.File.Name.End(), string(newName)) if err != nil { return err } edits[f.URI] = append(edits[f.URI], edit) } return nil } // renameImports computes the set of edits to imports resulting from renaming // the package described by the given metadata, to a package with import path // newPath and name newName. // // Edits are written into the edits map. func renameImports(ctx context.Context, snapshot *cache.Snapshot, mp *metadata.Package, newPath ImportPath, newName PackageName, allEdits map[protocol.DocumentURI][]diff.Edit) error { rdeps, err := snapshot.ReverseDependencies(ctx, mp.ID, false) // find direct importers if err != nil { return err } // Pass 1: rename import paths in import declarations. needsTypeCheck := make(map[PackageID][]protocol.DocumentURI) for _, rdep := range rdeps { if rdep.IsIntermediateTestVariant() { continue // for renaming, these variants are redundant } for _, uri := range rdep.CompiledGoFiles { fh, err := snapshot.ReadFile(ctx, uri) if err != nil { return err } f, err := snapshot.ParseGo(ctx, fh, parsego.Header) if err != nil { return err } if f.File.Name == nil { continue // no package declaration } for _, imp := range f.File.Imports { if rdep.DepsByImpPath[metadata.UnquoteImportPath(imp)] != mp.ID { continue // not the import we're looking for } // If the import does not explicitly specify // a local name, then we need to invoke the // type checker to locate references to update. // // TODO(adonovan): is this actually true? // Renaming an import with a local name can still // cause conflicts: shadowing of built-ins, or of // package-level decls in the same or another file. if imp.Name == nil { needsTypeCheck[rdep.ID] = append(needsTypeCheck[rdep.ID], uri) } // Create text edit for the import path (string literal). edit, err := posEdit(f.Tok, imp.Path.Pos(), imp.Path.End(), strconv.Quote(string(newPath))) if err != nil { return err } allEdits[uri] = append(allEdits[uri], edit) } } } // If the imported package's name hasn't changed, // we don't need to rename references within each file. if newName == mp.Name { return nil } // Pass 2: rename local name (types.PkgName) of imported // package throughout one or more files of the package. ids := make([]PackageID, 0, len(needsTypeCheck)) for id := range needsTypeCheck { ids = append(ids, id) } pkgs, err := snapshot.TypeCheck(ctx, ids...) if err != nil { return err } for i, id := range ids { pkg := pkgs[i] for _, uri := range needsTypeCheck[id] { f, err := pkg.File(uri) if err != nil { return err } for _, imp := range f.File.Imports { if imp.Name != nil { continue // has explicit local name } if rdeps[id].DepsByImpPath[metadata.UnquoteImportPath(imp)] != mp.ID { continue // not the import we're looking for } pkgname := pkg.TypesInfo().Implicits[imp].(*types.PkgName) pkgScope := pkg.Types().Scope() fileScope := pkg.TypesInfo().Scopes[f.File] localName := string(newName) try := 0 // Keep trying with fresh names until one succeeds. // // TODO(adonovan): fix: this loop is not sufficient to choose a name // that is guaranteed to be conflict-free; renameObj may still fail. // So the retry loop should be around renameObj, and we shouldn't // bother with scopes here. for fileScope.Lookup(localName) != nil || pkgScope.Lookup(localName) != nil { try++ localName = fmt.Sprintf("%s%d", newName, try) } // renameObj detects various conflicts, including: // - new name conflicts with a package-level decl in this file; // - new name hides a package-level decl in another file that // is actually referenced in this file; // - new name hides a built-in that is actually referenced // in this file; // - a reference in this file to the old package name would // become shadowed by an intervening declaration that // uses the new name. // It returns the edits if no conflict was detected. editMap, _, err := renameObjects(localName, pkg, pkgname) if err != nil { return err } // If the chosen local package name matches the package's // new name, delete the change that would have inserted // an explicit local name, which is always the lexically // first change. if localName == string(newName) { edits, ok := editMap[uri] if !ok { return fmt.Errorf("internal error: no changes for %s", uri) } diff.SortEdits(edits) editMap[uri] = edits[1:] } for uri, edits := range editMap { allEdits[uri] = append(allEdits[uri], edits...) } } } } return nil } // renameObjects computes the edits to the type-checked syntax package pkg // required to rename a set of target objects to newName. // // It also returns the set of objects that were found (due to // corresponding methods and embedded fields) to require renaming as a // consequence of the requested renamings. // // It returns an error if the renaming would cause a conflict. func renameObjects(newName string, pkg *cache.Package, targets ...types.Object) (map[protocol.DocumentURI][]diff.Edit, map[types.Object]bool, error) { r := renamer{ pkg: pkg, objsToUpdate: make(map[types.Object]bool), from: targets[0].Name(), to: newName, } // A renaming initiated at an interface method indicates the // intention to rename abstract and concrete methods as needed // to preserve assignability. // TODO(adonovan): pull this into the caller. for _, obj := range targets { if obj, ok := obj.(*types.Func); ok { recv := obj.Type().(*types.Signature).Recv() if recv != nil && types.IsInterface(recv.Type().Underlying()) { r.changeMethods = true break } } } // Check that the renaming of the identifier is ok. for _, obj := range targets { r.check(obj) if len(r.conflicts) > 0 { // Stop at first error. return nil, nil, fmt.Errorf("%s", strings.Join(r.conflicts, "\n")) } } editMap, err := r.update() if err != nil { return nil, nil, err } // Remove initial targets so that only 'consequences' remain. for _, obj := range targets { delete(r.objsToUpdate, obj) } return editMap, r.objsToUpdate, nil } // Rename all references to the target objects. func (r *renamer) update() (map[protocol.DocumentURI][]diff.Edit, error) { result := make(map[protocol.DocumentURI][]diff.Edit) // shouldUpdate reports whether obj is one of (or an // instantiation of one of) the target objects. shouldUpdate := func(obj types.Object) bool { return containsOrigin(r.objsToUpdate, obj) } // Find all identifiers in the package that define or use a // renamed object. We iterate over info as it is more efficient // than calling ast.Inspect for each of r.pkg.CompiledGoFiles(). type item struct { node ast.Node // Ident, ImportSpec (obj=PkgName), or CaseClause (obj=Var) obj types.Object isDef bool } var items []item info := r.pkg.TypesInfo() for id, obj := range info.Uses { if shouldUpdate(obj) { items = append(items, item{id, obj, false}) } } for id, obj := range info.Defs { if shouldUpdate(obj) { items = append(items, item{id, obj, true}) } } for node, obj := range info.Implicits { if shouldUpdate(obj) { switch node.(type) { case *ast.ImportSpec, *ast.CaseClause: items = append(items, item{node, obj, true}) } } } sort.Slice(items, func(i, j int) bool { return items[i].node.Pos() < items[j].node.Pos() }) // Update each identifier, and its doc comment if it is a declaration. for _, item := range items { pgf, ok := enclosingFile(r.pkg, item.node.Pos()) if !ok { bug.Reportf("edit does not belong to syntax of package %q", r.pkg) continue } // Renaming a types.PkgName may result in the addition or removal of an identifier, // so we deal with this separately. if pkgName, ok := item.obj.(*types.PkgName); ok && item.isDef { edit, err := r.updatePkgName(pgf, pkgName) if err != nil { return nil, err } result[pgf.URI] = append(result[pgf.URI], edit) continue } // Workaround the unfortunate lack of a Var object // for x in "switch x := expr.(type) {}" by adjusting // the case clause to the switch ident. // This may result in duplicate edits, but we de-dup later. if _, ok := item.node.(*ast.CaseClause); ok { path, _ := astutil.PathEnclosingInterval(pgf.File, item.obj.Pos(), item.obj.Pos()) item.node = path[0].(*ast.Ident) } // Replace the identifier with r.to. edit, err := posEdit(pgf.Tok, item.node.Pos(), item.node.End(), r.to) if err != nil { return nil, err } result[pgf.URI] = append(result[pgf.URI], edit) if !item.isDef { // uses do not have doc comments to update. continue } doc := docComment(pgf, item.node.(*ast.Ident)) if doc == nil { continue } // Perform the rename in doc comments declared in the original package. // go/parser strips out \r\n returns from the comment text, so go // line-by-line through the comment text to get the correct positions. docRegexp := regexp.MustCompile(`\b` + r.from + `\b`) // valid identifier => valid regexp for _, comment := range doc.List { if isDirective(comment.Text) { continue } // TODO(adonovan): why are we looping over lines? // Just run the loop body once over the entire multiline comment. lines := strings.Split(comment.Text, "\n") tokFile := pgf.Tok commentLine := safetoken.Line(tokFile, comment.Pos()) uri := protocol.URIFromPath(tokFile.Name()) for i, line := range lines { lineStart := comment.Pos() if i > 0 { lineStart = tokFile.LineStart(commentLine + i) } for _, locs := range docRegexp.FindAllIndex([]byte(line), -1) { edit, err := posEdit(tokFile, lineStart+token.Pos(locs[0]), lineStart+token.Pos(locs[1]), r.to) if err != nil { return nil, err // can't happen } result[uri] = append(result[uri], edit) } } } } docLinkEdits, err := r.updateCommentDocLinks() if err != nil { return nil, err } for uri, edits := range docLinkEdits { result[uri] = append(result[uri], edits...) } return result, nil } // updateCommentDocLinks updates each doc comment in the package // that refers to one of the renamed objects using a doc link // (https://golang.org/doc/comment#doclinks) such as "[pkg.Type.Method]". func (r *renamer) updateCommentDocLinks() (map[protocol.DocumentURI][]diff.Edit, error) { result := make(map[protocol.DocumentURI][]diff.Edit) var docRenamers []*docLinkRenamer for obj := range r.objsToUpdate { if _, ok := obj.(*types.PkgName); ok { // The dot package name will not be referenced if obj.Name() == "." { continue } docRenamers = append(docRenamers, &docLinkRenamer{ isDep: false, isPkgOrType: true, file: r.pkg.FileSet().File(obj.Pos()), regexp: docLinkPattern("", "", obj.Name(), true), to: r.to, }) continue } if !obj.Exported() { continue } recvName := "" // Doc links can reference only exported package-level objects // and methods of exported package-level named types. if !isPackageLevel(obj) { obj, isFunc := obj.(*types.Func) if !isFunc { continue } recv := obj.Type().(*types.Signature).Recv() if recv == nil { continue } _, named := typesinternal.ReceiverNamed(recv) if named == nil { continue } // Doc links can't reference interface methods. if types.IsInterface(named.Underlying()) { continue } name := named.Origin().Obj() if !name.Exported() || !isPackageLevel(name) { continue } recvName = name.Name() } // Qualify objects from other packages. pkgName := "" if r.pkg.Types() != obj.Pkg() { pkgName = obj.Pkg().Name() } _, isTypeName := obj.(*types.TypeName) docRenamers = append(docRenamers, &docLinkRenamer{ isDep: r.pkg.Types() != obj.Pkg(), isPkgOrType: isTypeName, packagePath: obj.Pkg().Path(), packageName: pkgName, recvName: recvName, objName: obj.Name(), regexp: docLinkPattern(pkgName, recvName, obj.Name(), isTypeName), to: r.to, }) } for _, pgf := range r.pkg.CompiledGoFiles() { for _, d := range docRenamers { edits, err := d.update(pgf) if err != nil { return nil, err } if len(edits) > 0 { result[pgf.URI] = append(result[pgf.URI], edits...) } } } return result, nil } // docLinkPattern returns a regular expression that matches doclinks in comments. // It has one submatch that indicates the symbol to be updated. func docLinkPattern(pkgName, recvName, objName string, isPkgOrType bool) *regexp.Regexp { // The doc link may contain a leading star, e.g. [*bytes.Buffer]. pattern := `\[\*?` if pkgName != "" { pattern += pkgName + `\.` } if recvName != "" { pattern += recvName + `\.` } // The first submatch is object name. pattern += `(` + objName + `)` // If the object is a *types.TypeName or *types.PkgName, also need // match the objects referenced by them, so add `(\.\w+)*`. if isPkgOrType { pattern += `(?:\.\w+)*` } // There are two type of link in comments: // 1. url link. e.g. [text]: url // 2. doc link. e.g. [pkg.Name] // in order to only match the doc link, add `([^:]|$)` in the end. pattern += `\](?:[^:]|$)` return regexp.MustCompile(pattern) } // A docLinkRenamer renames doc links of forms such as these: // // [Func] // [pkg.Func] // [RecvType.Method] // [*Type] // [*pkg.Type] // [*pkg.RecvType.Method] type docLinkRenamer struct { isDep bool // object is from a dependency package isPkgOrType bool // object is *types.PkgName or *types.TypeName packagePath string packageName string // e.g. "pkg" recvName string // e.g. "RecvType" objName string // e.g. "Func", "Type", "Method" to string // new name regexp *regexp.Regexp file *token.File // enclosing file, if renaming *types.PkgName } // update updates doc links in the package level comments. func (r *docLinkRenamer) update(pgf *parsego.File) (result []diff.Edit, err error) { if r.file != nil && r.file != pgf.Tok { return nil, nil } pattern := r.regexp // If the object is in dependency package, // the imported name in the file may be different from the original package name if r.isDep { for _, spec := range pgf.File.Imports { importPath, _ := strconv.Unquote(spec.Path.Value) if importPath == r.packagePath { // Ignore blank imports if spec.Name == nil || spec.Name.Name == "_" || spec.Name.Name == "." { continue } if spec.Name.Name != r.packageName { pattern = docLinkPattern(spec.Name.Name, r.recvName, r.objName, r.isPkgOrType) } break } } } var edits []diff.Edit updateDocLinks := func(doc *ast.CommentGroup) error { if doc != nil { for _, c := range doc.List { for _, locs := range pattern.FindAllStringSubmatchIndex(c.Text, -1) { // The first submatch is the object name, so the locs[2:4] is the index of object name. edit, err := posEdit(pgf.Tok, c.Pos()+token.Pos(locs[2]), c.Pos()+token.Pos(locs[3]), r.to) if err != nil { return err } edits = append(edits, edit) } } } return nil } // Update package doc comments. err = updateDocLinks(pgf.File.Doc) if err != nil { return nil, err } for _, decl := range pgf.File.Decls { var doc *ast.CommentGroup switch decl := decl.(type) { case *ast.GenDecl: doc = decl.Doc case *ast.FuncDecl: doc = decl.Doc } err = updateDocLinks(doc) if err != nil { return nil, err } } return edits, nil } // docComment returns the doc for an identifier within the specified file. func docComment(pgf *parsego.File, id *ast.Ident) *ast.CommentGroup { nodes, _ := astutil.PathEnclosingInterval(pgf.File, id.Pos(), id.End()) for _, node := range nodes { switch decl := node.(type) { case *ast.FuncDecl: return decl.Doc case *ast.Field: return decl.Doc case *ast.GenDecl: return decl.Doc // For {Type,Value}Spec, if the doc on the spec is absent, // search for the enclosing GenDecl case *ast.TypeSpec: if decl.Doc != nil { return decl.Doc } case *ast.ValueSpec: if decl.Doc != nil { return decl.Doc } case *ast.Ident: case *ast.AssignStmt: // *ast.AssignStmt doesn't have an associated comment group. // So, we try to find a comment just before the identifier. // Try to find a comment group only for short variable declarations (:=). if decl.Tok != token.DEFINE { return nil } identLine := safetoken.Line(pgf.Tok, id.Pos()) for _, comment := range nodes[len(nodes)-1].(*ast.File).Comments { if comment.Pos() > id.Pos() { // Comment is after the identifier. continue } lastCommentLine := safetoken.Line(pgf.Tok, comment.End()) if lastCommentLine+1 == identLine { return comment } } default: return nil } } return nil } // updatePkgName returns the updates to rename a pkgName in the import spec by // only modifying the package name portion of the import declaration. func (r *renamer) updatePkgName(pgf *parsego.File, pkgName *types.PkgName) (diff.Edit, error) { // Modify ImportSpec syntax to add or remove the Name as needed. path, _ := astutil.PathEnclosingInterval(pgf.File, pkgName.Pos(), pkgName.Pos()) if len(path) < 2 { return diff.Edit{}, fmt.Errorf("no path enclosing interval for %s", pkgName.Name()) } spec, ok := path[1].(*ast.ImportSpec) if !ok { return diff.Edit{}, fmt.Errorf("failed to update PkgName for %s", pkgName.Name()) } newText := "" if pkgName.Imported().Name() != r.to { newText = r.to + " " } // Replace the portion (possibly empty) of the spec before the path: // local "path" or "path" // -> <- -><- return posEdit(pgf.Tok, spec.Pos(), spec.Path.Pos(), newText) } // parsePackageNameDecl is a convenience function that parses and // returns the package name declaration of file fh, and reports // whether the position ppos lies within it. // // Note: also used by references. func parsePackageNameDecl(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, ppos protocol.Position) (*parsego.File, bool, error) { pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header) if err != nil { return nil, false, err } // Careful: because we used parsego.Header, // pgf.Pos(ppos) may be beyond EOF => (0, err). pos, _ := pgf.PositionPos(ppos) return pgf, pgf.File.Name.Pos() <= pos && pos <= pgf.File.Name.End(), nil } // enclosingFile returns the CompiledGoFile of pkg that contains the specified position. func enclosingFile(pkg *cache.Package, pos token.Pos) (*parsego.File, bool) { for _, pgf := range pkg.CompiledGoFiles() { if pgf.File.Pos() <= pos && pos <= pgf.File.End() { return pgf, true } } return nil, false } // posEdit returns an edit to replace the (start, end) range of tf with 'new'. func posEdit(tf *token.File, start, end token.Pos, new string) (diff.Edit, error) { startOffset, endOffset, err := safetoken.Offsets(tf, start, end) if err != nil { return diff.Edit{}, err } return diff.Edit{Start: startOffset, End: endOffset, New: new}, nil }
tools/gopls/internal/golang/rename.go/0
{ "file_path": "tools/gopls/internal/golang/rename.go", "repo_id": "tools", "token_count": 16572 }
743
// 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 lsprpc import ( "fmt" "os/exec" ) var ( daemonize = func(*exec.Cmd) {} autoNetworkAddress = autoNetworkAddressDefault verifyRemoteOwnership = verifyRemoteOwnershipDefault ) func runRemote(cmd *exec.Cmd) error { daemonize(cmd) if err := cmd.Start(); err != nil { return fmt.Errorf("starting remote gopls: %w", err) } return nil } // autoNetworkAddressDefault returns the default network and address for the // automatically-started gopls remote. See autostart_posix.go for more // information. func autoNetworkAddressDefault(goplsPath, id string) (network string, address string) { if id != "" { panic("identified remotes are not supported on windows") } return "tcp", "localhost:37374" } func verifyRemoteOwnershipDefault(network, address string) (bool, error) { return true, nil }
tools/gopls/internal/lsprpc/autostart_default.go/0
{ "file_path": "tools/gopls/internal/lsprpc/autostart_default.go", "repo_id": "tools", "token_count": 316 }
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. package mod import ( "context" "fmt" "golang.org/x/mod/modfile" "golang.org/x/tools/gopls/internal/cache" "golang.org/x/tools/gopls/internal/file" "golang.org/x/tools/gopls/internal/protocol" ) func InlayHint(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, _ protocol.Range) ([]protocol.InlayHint, error) { // Inlay hints are enabled if the client supports them. pm, err := snapshot.ParseMod(ctx, fh) if err != nil { return nil, err } // Compare the version of the module used in the snapshot's // metadata (i.e. the solution to the MVS constraints computed // by go list) with the version requested by the module, in // both cases, taking replaces into account. Produce an // InlayHint when the version of the module is not the one // used. replaces := make(map[string]*modfile.Replace) for _, x := range pm.File.Replace { replaces[x.Old.Path] = x } requires := make(map[string]*modfile.Require) for _, x := range pm.File.Require { requires[x.Mod.Path] = x } am, err := snapshot.AllMetadata(ctx) if err != nil { return nil, err } var ans []protocol.InlayHint seen := make(map[string]bool) for _, meta := range am { if meta.Module == nil || seen[meta.Module.Path] { continue } seen[meta.Module.Path] = true metaVersion := meta.Module.Version if meta.Module.Replace != nil { metaVersion = meta.Module.Replace.Version } // These versions can be blank, as in gopls/go.mod's local replace if oldrepl, ok := replaces[meta.Module.Path]; ok && oldrepl.New.Version != metaVersion { ih := genHint(oldrepl.Syntax, oldrepl.New.Version, metaVersion, pm.Mapper) if ih != nil { ans = append(ans, *ih) } } else if oldreq, ok := requires[meta.Module.Path]; ok && oldreq.Mod.Version != metaVersion { // maybe it was replaced: if _, ok := replaces[meta.Module.Path]; ok { continue } ih := genHint(oldreq.Syntax, oldreq.Mod.Version, metaVersion, pm.Mapper) if ih != nil { ans = append(ans, *ih) } } } return ans, nil } func genHint(mline *modfile.Line, oldVersion, newVersion string, m *protocol.Mapper) *protocol.InlayHint { x := mline.End.Byte // the parser has removed trailing whitespace and comments (see modfile_test.go) x -= len(mline.Token[len(mline.Token)-1]) line, err := m.OffsetPosition(x) if err != nil { return nil } part := protocol.InlayHintLabelPart{ Value: newVersion, Tooltip: &protocol.OrPTooltipPLabel{ Value: fmt.Sprintf("The build selects version %s rather than go.mod's version %s.", newVersion, oldVersion), }, } rng, err := m.OffsetRange(x, mline.End.Byte) if err != nil { return nil } te := protocol.TextEdit{ Range: rng, NewText: newVersion, } return &protocol.InlayHint{ Position: line, Label: []protocol.InlayHintLabelPart{part}, Kind: protocol.Parameter, PaddingRight: true, TextEdits: []protocol.TextEdit{te}, } }
tools/gopls/internal/mod/inlayhint.go/0
{ "file_path": "tools/gopls/internal/mod/inlayhint.go", "repo_id": "tools", "token_count": 1179 }
745
// 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. // The generate command generates Go declarations from VSCode's // description of the Language Server Protocol. // // To run it, type 'go generate' in the parent (protocol) directory. package main // see https://github.com/golang/go/issues/61217 for discussion of an issue import ( "bytes" "encoding/json" "flag" "fmt" "go/format" "log" "os" "os/exec" "path/filepath" "strings" ) const vscodeRepo = "https://github.com/microsoft/vscode-languageserver-node" // lspGitRef names a branch or tag in vscodeRepo. // It implicitly determines the protocol version of the LSP used by gopls. // For example, tag release/protocol/3.17.3 of the repo defines // protocol version 3.17.0 (as declared by the metaData.version field). // (Point releases are reflected in the git tag version even when they are cosmetic // and don't change the protocol.) var lspGitRef = "release/protocol/3.17.6-next.2" var ( repodir = flag.String("d", "", "directory containing clone of "+vscodeRepo) outputdir = flag.String("o", ".", "output directory") // PJW: not for real code cmpdir = flag.String("c", "", "directory of earlier code") doboth = flag.String("b", "", "generate and compare") lineNumbers = flag.Bool("l", false, "add line numbers to generated output") ) func main() { log.SetFlags(log.Lshortfile) // log file name and line number, not time flag.Parse() processinline() } func processinline() { // A local repository may be specified during debugging. // The default behavior is to download the canonical version. if *repodir == "" { tmpdir, err := os.MkdirTemp("", "") if err != nil { log.Fatal(err) } defer os.RemoveAll(tmpdir) // ignore error // Clone the repository. cmd := exec.Command("git", "clone", "--quiet", "--depth=1", "-c", "advice.detachedHead=false", vscodeRepo, "--branch="+lspGitRef, "--single-branch", tmpdir) cmd.Stdout = os.Stderr cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { log.Fatal(err) } *repodir = tmpdir } else { lspGitRef = fmt.Sprintf("(not git, local dir %s)", *repodir) } model := parse(filepath.Join(*repodir, "protocol/metaModel.json")) findTypeNames(model) generateOutput(model) fileHdr = fileHeader(model) // write the files writeclient() writeserver() writeprotocol() writejsons() checkTables() } // common file header for output files var fileHdr string func writeclient() { out := new(bytes.Buffer) fmt.Fprintln(out, fileHdr) out.WriteString( `import ( "context" "golang.org/x/tools/internal/jsonrpc2" ) `) out.WriteString("type Client interface {\n") for _, k := range cdecls.keys() { out.WriteString(cdecls[k]) } out.WriteString("}\n\n") out.WriteString(`func clientDispatch(ctx context.Context, client Client, reply jsonrpc2.Replier, r jsonrpc2.Request) (bool, error) { defer recoverHandlerPanic(r.Method()) switch r.Method() { `) for _, k := range ccases.keys() { out.WriteString(ccases[k]) } out.WriteString(("\tdefault:\n\t\treturn false, nil\n\t}\n}\n\n")) for _, k := range cfuncs.keys() { out.WriteString(cfuncs[k]) } formatTo("tsclient.go", out.Bytes()) } func writeserver() { out := new(bytes.Buffer) fmt.Fprintln(out, fileHdr) out.WriteString( `import ( "context" "golang.org/x/tools/internal/jsonrpc2" ) `) out.WriteString("type Server interface {\n") for _, k := range sdecls.keys() { out.WriteString(sdecls[k]) } out.WriteString(` } func serverDispatch(ctx context.Context, server Server, reply jsonrpc2.Replier, r jsonrpc2.Request) (bool, error) { defer recoverHandlerPanic(r.Method()) switch r.Method() { `) for _, k := range scases.keys() { out.WriteString(scases[k]) } out.WriteString(("\tdefault:\n\t\treturn false, nil\n\t}\n}\n\n")) for _, k := range sfuncs.keys() { out.WriteString(sfuncs[k]) } formatTo("tsserver.go", out.Bytes()) } func writeprotocol() { out := new(bytes.Buffer) fmt.Fprintln(out, fileHdr) out.WriteString("import \"encoding/json\"\n\n") // The following are unneeded, but make the new code a superset of the old hack := func(newer, existing string) { if _, ok := types[existing]; !ok { log.Fatalf("types[%q] not found", existing) } types[newer] = strings.Replace(types[existing], existing, newer, 1) } hack("ConfigurationParams", "ParamConfiguration") hack("InitializeParams", "ParamInitialize") hack("PreviousResultId", "PreviousResultID") hack("WorkspaceFoldersServerCapabilities", "WorkspaceFolders5Gn") hack("_InitializeParams", "XInitializeParams") for _, k := range types.keys() { if k == "WatchKind" { types[k] = "type WatchKind = uint32" // strict gopls compatibility needs the '=' } out.WriteString(types[k]) } out.WriteString("\nconst (\n") for _, k := range consts.keys() { out.WriteString(consts[k]) } out.WriteString(")\n\n") formatTo("tsprotocol.go", out.Bytes()) } func writejsons() { out := new(bytes.Buffer) fmt.Fprintln(out, fileHdr) out.WriteString("import \"encoding/json\"\n\n") out.WriteString("import \"fmt\"\n") out.WriteString(` // 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 } `) for _, k := range jsons.keys() { out.WriteString(jsons[k]) } formatTo("tsjson.go", out.Bytes()) } // formatTo formats the Go source and writes it to *outputdir/basename. func formatTo(basename string, src []byte) { formatted, err := format.Source(src) if err != nil { failed := filepath.Join("/tmp", basename+".fail") os.WriteFile(failed, src, 0644) log.Fatalf("formatting %s: %v (see %s)", basename, err, failed) } if err := os.WriteFile(filepath.Join(*outputdir, basename), formatted, 0644); err != nil { log.Fatal(err) } } // create the common file header for the output files func fileHeader(model *Model) string { fname := filepath.Join(*repodir, ".git", "HEAD") buf, err := os.ReadFile(fname) if err != nil { log.Fatal(err) } buf = bytes.TrimSpace(buf) var githash string if len(buf) == 40 { githash = string(buf[:40]) } else if bytes.HasPrefix(buf, []byte("ref: ")) { fname = filepath.Join(*repodir, ".git", string(buf[5:])) buf, err = os.ReadFile(fname) if err != nil { log.Fatal(err) } githash = string(buf[:40]) } else { log.Fatalf("githash cannot be recovered from %s", fname) } format := `// 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 %[1]s at ref %[2]s (hash %[3]s). // %[4]s/blob/%[2]s/%[1]s // LSP metaData.version = %[5]s. ` return fmt.Sprintf(format, "protocol/metaModel.json", // 1 lspGitRef, // 2 githash, // 3 vscodeRepo, // 4 model.Version.Version) // 5 } func parse(fname string) *Model { buf, err := os.ReadFile(fname) if err != nil { log.Fatal(err) } buf = addLineNumbers(buf) model := new(Model) if err := json.Unmarshal(buf, model); err != nil { log.Fatal(err) } return model } // Type.Value has to be treated specially for literals and maps func (t *Type) UnmarshalJSON(data []byte) error { // First unmarshal only the unambiguous fields. var x struct { Kind string `json:"kind"` Items []*Type `json:"items"` Element *Type `json:"element"` Name string `json:"name"` Key *Type `json:"key"` Value any `json:"value"` Line int `json:"line"` } if err := json.Unmarshal(data, &x); err != nil { return err } *t = Type{ Kind: x.Kind, Items: x.Items, Element: x.Element, Name: x.Name, Value: x.Value, Line: x.Line, } // Then unmarshal the 'value' field based on the kind. // This depends on Unmarshal ignoring fields it doesn't know about. switch x.Kind { case "map": var x struct { Key *Type `json:"key"` Value *Type `json:"value"` } if err := json.Unmarshal(data, &x); err != nil { return fmt.Errorf("Type.kind=map: %v", err) } t.Key = x.Key t.Value = x.Value case "literal": var z struct { Value ParseLiteral `json:"value"` } if err := json.Unmarshal(data, &z); err != nil { return fmt.Errorf("Type.kind=literal: %v", err) } t.Value = z.Value case "base", "reference", "array", "and", "or", "tuple", "stringLiteral": // no-op. never seen integerLiteral or booleanLiteral. default: return fmt.Errorf("cannot decode Type.kind %q: %s", x.Kind, data) } return nil } // which table entries were not used func checkTables() { for k := range disambiguate { if !usedDisambiguate[k] { log.Printf("disambiguate[%v] unused", k) } } for k := range renameProp { if !usedRenameProp[k] { log.Printf("renameProp {%q, %q} unused", k[0], k[1]) } } for k := range goplsStar { if !usedGoplsStar[k] { log.Printf("goplsStar {%q, %q} unused", k[0], k[1]) } } for k := range goplsType { if !usedGoplsType[k] { log.Printf("unused goplsType[%q]->%s", k, goplsType[k]) } } }
tools/gopls/internal/protocol/generate/main.go/0
{ "file_path": "tools/gopls/internal/protocol/generate/main.go", "repo_id": "tools", "token_count": 3692 }
746
// 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 protocol import ( "encoding/json" "fmt" ) // InsertReplaceEdit is used instead of TextEdit in CompletionItem // in editors that support it. These two types are alike in appearance // but can be differentiated by the presence or absence of // certain properties. UnmarshalJSON of the sum type tries to // unmarshal as TextEdit only if unmarshal as InsertReplaceEdit fails. // However, due to this similarity, unmarshal with the other type // never fails. This file has a custom JSON unmarshaller for // InsertReplaceEdit, that fails if the required fields are missing. // UnmarshalJSON unmarshals InsertReplaceEdit with extra // checks on the presence of "insert" and "replace" properties. func (e *InsertReplaceEdit) UnmarshalJSON(data []byte) error { var required struct { NewText string Insert *Range `json:"insert,omitempty"` Replace *Range `json:"replace,omitempty"` } if err := json.Unmarshal(data, &required); err != nil { return err } if required.Insert == nil && required.Replace == nil { return fmt.Errorf("not InsertReplaceEdit") } e.NewText = required.NewText e.Insert = *required.Insert e.Replace = *required.Replace return nil }
tools/gopls/internal/protocol/tsinsertreplaceedit.go/0
{ "file_path": "tools/gopls/internal/protocol/tsinsertreplaceedit.go", "repo_id": "tools", "token_count": 398 }
747
// 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 import ( "context" "fmt" "strings" "golang.org/x/tools/gopls/internal/file" "golang.org/x/tools/gopls/internal/golang" "golang.org/x/tools/gopls/internal/golang/completion" "golang.org/x/tools/gopls/internal/label" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/settings" "golang.org/x/tools/gopls/internal/telemetry" "golang.org/x/tools/gopls/internal/template" "golang.org/x/tools/gopls/internal/work" "golang.org/x/tools/internal/event" ) func (s *server) Completion(ctx context.Context, params *protocol.CompletionParams) (_ *protocol.CompletionList, rerr error) { recordLatency := telemetry.StartLatencyTimer("completion") defer func() { recordLatency(ctx, rerr) }() ctx, done := event.Start(ctx, "lsp.Server.completion", label.URI.Of(params.TextDocument.URI)) defer done() fh, snapshot, release, err := s.fileOf(ctx, params.TextDocument.URI) if err != nil { return nil, err } defer release() var candidates []completion.CompletionItem var surrounding *completion.Selection switch snapshot.FileKind(fh) { case file.Go: candidates, surrounding, err = completion.Completion(ctx, snapshot, fh, params.Position, params.Context) case file.Mod: candidates, surrounding = nil, nil case file.Work: cl, err := work.Completion(ctx, snapshot, fh, params.Position) if err != nil { break } return cl, nil case file.Tmpl: var cl *protocol.CompletionList cl, err = template.Completion(ctx, snapshot, fh, params.Position, params.Context) if err != nil { break // use common error handling, candidates==nil } return cl, nil } if err != nil { event.Error(ctx, "no completions found", err, label.Position.Of(params.Position)) } if candidates == nil || surrounding == nil { complEmpty.Inc() return &protocol.CompletionList{ IsIncomplete: true, Items: []protocol.CompletionItem{}, }, nil } // When using deep completions/fuzzy matching, report results as incomplete so // client fetches updated completions after every key stroke. options := snapshot.Options() incompleteResults := options.DeepCompletion || options.Matcher == settings.Fuzzy items, err := toProtocolCompletionItems(candidates, surrounding, options) if err != nil { return nil, err } if snapshot.FileKind(fh) == file.Go { s.saveLastCompletion(fh.URI(), fh.Version(), items, params.Position) } if len(items) > 10 { // TODO(pjw): long completions are ok for field lists complLong.Inc() } else { complShort.Inc() } return &protocol.CompletionList{ IsIncomplete: incompleteResults, Items: items, }, nil } func (s *server) saveLastCompletion(uri protocol.DocumentURI, version int32, items []protocol.CompletionItem, pos protocol.Position) { s.efficacyMu.Lock() defer s.efficacyMu.Unlock() s.efficacyVersion = version s.efficacyURI = uri s.efficacyPos = pos s.efficacyItems = items } func toProtocolCompletionItems(candidates []completion.CompletionItem, surrounding *completion.Selection, options *settings.Options) ([]protocol.CompletionItem, error) { replaceRng, err := surrounding.Range() if err != nil { return nil, err } insertRng0, err := surrounding.PrefixRange() if err != nil { return nil, err } suffix := surrounding.Suffix() var ( items = make([]protocol.CompletionItem, 0, len(candidates)) numDeepCompletionsSeen int ) for i, candidate := range candidates { // Limit the number of deep completions to not overwhelm the user in cases // with dozens of deep completion matches. if candidate.Depth > 0 { if !options.DeepCompletion { continue } if numDeepCompletionsSeen >= completion.MaxDeepCompletions { continue } numDeepCompletionsSeen++ } insertText := candidate.InsertText if options.InsertTextFormat == protocol.SnippetTextFormat { insertText = candidate.Snippet() } // This can happen if the client has snippets disabled but the // candidate only supports snippet insertion. if insertText == "" { continue } doc := &protocol.Or_CompletionItem_documentation{ Value: protocol.MarkupContent{ Kind: protocol.Markdown, Value: golang.CommentToMarkdown(candidate.Documentation, options), }, } if options.PreferredContentFormat != protocol.Markdown { doc.Value = candidate.Documentation } var edits *protocol.Or_CompletionItem_textEdit if options.InsertReplaceSupported { insertRng := insertRng0 if suffix == "" || strings.Contains(insertText, suffix) { insertRng = replaceRng } // Insert and Replace ranges share the same start position and // the same text edit but the end position may differ. // See the comment for the CompletionItem's TextEdit field. // https://pkg.go.dev/golang.org/x/tools/gopls/internal/protocol#CompletionItem edits = &protocol.Or_CompletionItem_textEdit{ Value: protocol.InsertReplaceEdit{ NewText: insertText, Insert: insertRng, // replace up to the cursor position. Replace: replaceRng, }, } } else { edits = &protocol.Or_CompletionItem_textEdit{ Value: protocol.TextEdit{ NewText: insertText, Range: replaceRng, }, } } item := protocol.CompletionItem{ Label: candidate.Label, Detail: candidate.Detail, Kind: candidate.Kind, TextEdit: edits, InsertTextFormat: &options.InsertTextFormat, AdditionalTextEdits: candidate.AdditionalTextEdits, // This is a hack so that the client sorts completion results in the order // according to their score. This can be removed upon the resolution of // https://github.com/Microsoft/language-server-protocol/issues/348. SortText: fmt.Sprintf("%05d", i), // Trim operators (VSCode doesn't like weird characters in // filterText). FilterText: strings.TrimLeft(candidate.InsertText, "&*"), Preselect: i == 0, Documentation: doc, Tags: protocol.NonNilSlice(candidate.Tags), Deprecated: candidate.Deprecated, } items = append(items, item) } return items, nil }
tools/gopls/internal/server/completion.go/0
{ "file_path": "tools/gopls/internal/server/completion.go", "repo_id": "tools", "token_count": 2303 }
748
// 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 server import ( "context" "fmt" "golang.org/x/tools/go/ast/astutil" "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/internal/event" ) // selectionRange defines the textDocument/selectionRange feature, // which, given a list of positions within a file, // reports a linked list of enclosing syntactic blocks, innermost first. // // See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_selectionRange. // // This feature can be used by a client to implement "expand selection" in a // language-aware fashion. Multiple input positions are supported to allow // for multiple cursors, and the entire path up to the whole document is // returned for each cursor to avoid multiple round-trips when the user is // likely to issue this command multiple times in quick succession. func (s *server) SelectionRange(ctx context.Context, params *protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) { ctx, done := event.Start(ctx, "lsp.Server.selectionRange") defer done() fh, snapshot, release, err := s.fileOf(ctx, params.TextDocument.URI) if err != nil { return nil, err } defer release() if kind := snapshot.FileKind(fh); kind != file.Go { return nil, fmt.Errorf("SelectionRange not supported for file of type %s", kind) } pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full) if err != nil { return nil, err } result := make([]protocol.SelectionRange, len(params.Positions)) for i, protocolPos := range params.Positions { pos, err := pgf.PositionPos(protocolPos) if err != nil { return nil, err } path, _ := astutil.PathEnclosingInterval(pgf.File, pos, pos) tail := &result[i] // tail of the Parent linked list, built head first for j, node := range path { rng, err := pgf.NodeRange(node) if err != nil { return nil, err } // Add node to tail. if j > 0 { tail.Parent = &protocol.SelectionRange{} tail = tail.Parent } tail.Range = rng } } return result, nil }
tools/gopls/internal/server/selection_range.go/0
{ "file_path": "tools/gopls/internal/server/selection_range.go", "repo_id": "tools", "token_count": 777 }
749
// 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 go1.20 // +build go1.20 package settings import "testing" func TestFixLangVersion(t *testing.T) { tests := []struct { input, want string wantErr bool }{ {"", "", false}, {"1.18", "1.18", false}, {"v1.18", "v1.18", false}, {"1.21", "1.21", false}, {"1.21rc3", "1.21", false}, {"1.21.0", "1.21.0", false}, {"1.21.1", "1.21.1", false}, {"v1.21.1", "v1.21.1", false}, {"v1.21.0rc1", "v1.21.0", false}, // not technically valid, but we're flexible {"v1.21.0.0", "v1.21.0", false}, // also technically invalid {"1.1", "1.1", false}, {"v1", "v1", false}, {"1", "1", false}, {"v1.21.", "v1.21", false}, // also invalid {"1.21.", "1.21", false}, // Error cases. {"rc1", "", true}, {"x1.2.3", "", true}, } for _, test := range tests { got, err := fixLangVersion(test.input) if test.wantErr { if err == nil { t.Errorf("fixLangVersion(%q) succeeded unexpectedly", test.input) } continue } if err != nil { t.Fatalf("fixLangVersion(%q) failed: %v", test.input, err) } if got != test.want { t.Errorf("fixLangVersion(%q) = %s, want %s", test.input, got, test.want) } } }
tools/gopls/internal/settings/gofumpt_120_test.go/0
{ "file_path": "tools/gopls/internal/settings/gofumpt_120_test.go", "repo_id": "tools", "token_count": 592 }
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 bench import ( "bytes" "compress/gzip" "context" "flag" "fmt" "io" "log" "os" "os/exec" "path/filepath" "strings" "sync" "testing" "time" "golang.org/x/tools/gopls/internal/cmd" "golang.org/x/tools/gopls/internal/protocol/command" "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/event" "golang.org/x/tools/internal/fakenet" "golang.org/x/tools/internal/jsonrpc2" "golang.org/x/tools/internal/jsonrpc2/servertest" "golang.org/x/tools/internal/pprof" "golang.org/x/tools/internal/tool" ) var ( goplsPath = flag.String("gopls_path", "", "if set, use this gopls for testing; incompatible with -gopls_commit") installGoplsOnce sync.Once // guards installing gopls at -gopls_commit goplsCommit = flag.String("gopls_commit", "", "if set, install and use gopls at this commit for testing; incompatible with -gopls_path") cpuProfile = flag.String("gopls_cpuprofile", "", "if set, the cpu profile file suffix; see \"Profiling\" in the package doc") memProfile = flag.String("gopls_memprofile", "", "if set, the mem profile file suffix; see \"Profiling\" in the package doc") allocProfile = flag.String("gopls_allocprofile", "", "if set, the alloc profile file suffix; see \"Profiling\" in the package doc") trace = flag.String("gopls_trace", "", "if set, the trace file suffix; see \"Profiling\" in the package doc") // If non-empty, tempDir is a temporary working dir that was created by this // test suite. makeTempDirOnce sync.Once // guards creation of the temp dir tempDir string ) // if runAsGopls is "true", run the gopls command instead of the testing.M. const runAsGopls = "_GOPLS_BENCH_RUN_AS_GOPLS" func TestMain(m *testing.M) { bug.PanicOnBugs = true if os.Getenv(runAsGopls) == "true" { tool.Main(context.Background(), cmd.New(), os.Args[1:]) os.Exit(0) } event.SetExporter(nil) // don't log to stderr code := m.Run() if err := cleanup(); err != nil { fmt.Fprintf(os.Stderr, "cleaning up after benchmarks: %v\n", err) if code == 0 { code = 1 } } os.Exit(code) } // getTempDir returns the temporary directory to use for benchmark files, // creating it if necessary. func getTempDir() string { makeTempDirOnce.Do(func() { var err error tempDir, err = os.MkdirTemp("", "gopls-bench") if err != nil { log.Fatal(err) } }) return tempDir } // shallowClone performs a shallow clone of repo into dir at the given // 'commitish' ref (any commit reference understood by git). // // The directory dir must not already exist. func shallowClone(dir, repo, commitish string) error { if err := os.Mkdir(dir, 0750); err != nil { return fmt.Errorf("creating dir for %s: %v", repo, err) } // Set a timeout for git fetch. If this proves flaky, it can be removed. ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() // Use a shallow fetch to download just the relevant commit. shInit := fmt.Sprintf("git init && git fetch --depth=1 %q %q && git checkout FETCH_HEAD", repo, commitish) initCmd := exec.CommandContext(ctx, "/bin/sh", "-c", shInit) initCmd.Dir = dir if output, err := initCmd.CombinedOutput(); err != nil { return fmt.Errorf("checking out %s: %v\n%s", repo, err, output) } return nil } // connectEditor connects a fake editor session in the given dir, using the // given editor config. func connectEditor(dir string, config fake.EditorConfig, ts servertest.Connector) (*fake.Sandbox, *fake.Editor, *integration.Awaiter, error) { s, err := fake.NewSandbox(&fake.SandboxConfig{ Workdir: dir, GOPROXY: "https://proxy.golang.org", }) if err != nil { return nil, nil, nil, err } a := integration.NewAwaiter(s.Workdir) editor, err := fake.NewEditor(s, config).Connect(context.Background(), ts, a.Hooks()) if err != nil { return nil, nil, nil, err } return s, editor, a, nil } // newGoplsConnector returns a connector that connects to a new gopls process, // executed with the provided arguments. func newGoplsConnector(args []string) (servertest.Connector, error) { if *goplsPath != "" && *goplsCommit != "" { panic("can't set both -gopls_path and -gopls_commit") } var ( goplsPath = *goplsPath env []string ) if *goplsCommit != "" { goplsPath = getInstalledGopls() } if goplsPath == "" { var err error goplsPath, err = os.Executable() if err != nil { return nil, err } env = []string{fmt.Sprintf("%s=true", runAsGopls)} } return &SidecarServer{ goplsPath: goplsPath, env: env, args: args, }, nil } // profileArgs returns additional command-line arguments to use when invoking // gopls, to enable the user-requested profiles. // // If wantCPU is set, CPU profiling is enabled as well. Some tests may want to // instrument profiling around specific critical sections of the benchmark, // rather than the entire process. // // TODO(rfindley): like CPU, all of these would be better served by a custom // command. Very rarely do we care about memory usage as the process exits: we // care about specific points in time during the benchmark. mem and alloc // should be snapshotted, and tracing should be bracketed around critical // sections. func profileArgs(name string, wantCPU bool) []string { var args []string if wantCPU && *cpuProfile != "" { args = append(args, fmt.Sprintf("-profile.cpu=%s", qualifiedName(name, *cpuProfile))) } if *memProfile != "" { args = append(args, fmt.Sprintf("-profile.mem=%s", qualifiedName(name, *memProfile))) } if *allocProfile != "" { args = append(args, fmt.Sprintf("-profile.alloc=%s", qualifiedName(name, *allocProfile))) } if *trace != "" { args = append(args, fmt.Sprintf("-profile.trace=%s", qualifiedName(name, *trace))) } return args } func qualifiedName(args ...string) string { return strings.Join(args, ".") } // getInstalledGopls builds gopls at the given -gopls_commit, returning the // path to the gopls binary. func getInstalledGopls() string { if *goplsCommit == "" { panic("must provide -gopls_commit") } toolsDir := filepath.Join(getTempDir(), "gopls_build") goplsPath := filepath.Join(toolsDir, "gopls", "gopls") installGoplsOnce.Do(func() { log.Printf("installing gopls: checking out x/tools@%s into %s\n", *goplsCommit, toolsDir) if err := shallowClone(toolsDir, "https://go.googlesource.com/tools", *goplsCommit); err != nil { log.Fatal(err) } log.Println("installing gopls: building...") bld := exec.Command("go", "build", ".") bld.Dir = filepath.Join(toolsDir, "gopls") if output, err := bld.CombinedOutput(); err != nil { log.Fatalf("building gopls: %v\n%s", err, output) } // Confirm that the resulting path now exists. if _, err := os.Stat(goplsPath); err != nil { log.Fatalf("os.Stat(%s): %v", goplsPath, err) } }) return goplsPath } // A SidecarServer starts (and connects to) a separate gopls process at the // given path. type SidecarServer struct { goplsPath string env []string // additional environment bindings args []string // command-line arguments } // Connect creates new io.Pipes and binds them to the underlying StreamServer. // // It implements the servertest.Connector interface. func (s *SidecarServer) Connect(ctx context.Context) jsonrpc2.Conn { // Note: don't use CommandContext here, as we want gopls to exit gracefully // in order to write out profile data. // // We close the connection on context cancelation below. cmd := exec.Command(s.goplsPath, s.args...) stdin, err := cmd.StdinPipe() if err != nil { log.Fatal(err) } stdout, err := cmd.StdoutPipe() if err != nil { log.Fatal(err) } cmd.Stderr = os.Stderr cmd.Env = append(os.Environ(), s.env...) if err := cmd.Start(); err != nil { log.Fatalf("starting gopls: %v", err) } go func() { // If we don't log.Fatal here, benchmarks may hang indefinitely if gopls // exits abnormally. // // TODO(rfindley): ideally we would shut down the connection gracefully, // but that doesn't currently work. if err := cmd.Wait(); err != nil { log.Fatalf("gopls invocation failed with error: %v", err) } }() clientStream := jsonrpc2.NewHeaderStream(fakenet.NewConn("stdio", stdout, stdin)) clientConn := jsonrpc2.NewConn(clientStream) go func() { select { case <-ctx.Done(): clientConn.Close() clientStream.Close() case <-clientConn.Done(): } }() return clientConn } // startProfileIfSupported checks to see if the remote gopls instance supports // the start/stop profiling commands. If so, it starts profiling and returns a // function that stops profiling and records the total CPU seconds sampled in the // cpu_seconds benchmark metric. // // If the remote gopls instance does not support profiling commands, this // function returns nil. // // If the supplied userSuffix is non-empty, the profile is written to // <repo>.<userSuffix>, and not deleted when the benchmark exits. Otherwise, // the profile is written to a temp file that is deleted after the cpu_seconds // metric has been computed. func startProfileIfSupported(b *testing.B, env *integration.Env, name string) func() { if !env.Editor.HasCommand(command.StartProfile) { return nil } b.StopTimer() stopProfile := env.StartProfile() b.StartTimer() return func() { b.StopTimer() profFile := stopProfile() totalCPU, err := totalCPUForProfile(profFile) if err != nil { b.Fatalf("reading profile: %v", err) } b.ReportMetric(totalCPU.Seconds()/float64(b.N), "cpu_seconds/op") if *cpuProfile == "" { // The user didn't request profiles, so delete it to clean up. if err := os.Remove(profFile); err != nil { b.Errorf("removing profile file: %v", err) } } else { // NOTE: if this proves unreliable (due to e.g. EXDEV), we can fall back // on Read+Write+Remove. name := qualifiedName(name, *cpuProfile) if err := os.Rename(profFile, name); err != nil { b.Fatalf("renaming profile file: %v", err) } } } } // totalCPUForProfile reads the pprof profile with the given file name, parses, // and aggregates the total CPU sampled during the profile. func totalCPUForProfile(filename string) (time.Duration, error) { protoGz, err := os.ReadFile(filename) if err != nil { return 0, err } rd, err := gzip.NewReader(bytes.NewReader(protoGz)) if err != nil { return 0, fmt.Errorf("creating gzip reader for %s: %v", filename, err) } data, err := io.ReadAll(rd) if err != nil { return 0, fmt.Errorf("reading %s: %v", filename, err) } return pprof.TotalTime(data) } // closeBuffer stops the benchmark timer and closes the buffer with the given // name. // // It may be used to clean up files opened in the shared environment during // benchmarking. func closeBuffer(b *testing.B, env *integration.Env, name string) { b.StopTimer() env.CloseBuffer(name) env.AfterChange() b.StartTimer() }
tools/gopls/internal/test/integration/bench/bench_test.go/0
{ "file_path": "tools/gopls/internal/test/integration/bench/bench_test.go", "repo_id": "tools", "token_count": 3965 }
751
// 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 bench import ( "flag" "fmt" "testing" ) var symbolQuery = flag.String("symbol_query", "test", "symbol query to use in benchmark") // BenchmarkWorkspaceSymbols benchmarks the time to execute a workspace symbols // request (controlled by the -symbol_query flag). func BenchmarkWorkspaceSymbols(b *testing.B) { for name := range repos { b.Run(name, func(b *testing.B) { env := getRepo(b, name).sharedEnv(b) symbols := env.Symbol(*symbolQuery) // warm the cache if testing.Verbose() { fmt.Println("Results:") for i, symbol := range symbols { fmt.Printf("\t%d. %s (%s)\n", i, symbol.Name, symbol.ContainerName) } } b.ResetTimer() if stopAndRecord := startProfileIfSupported(b, env, qualifiedName(name, "workspaceSymbols")); stopAndRecord != nil { defer stopAndRecord() } for i := 0; i < b.N; i++ { env.Symbol(*symbolQuery) } }) } }
tools/gopls/internal/test/integration/bench/workspace_symbols_test.go/0
{ "file_path": "tools/gopls/internal/test/integration/bench/workspace_symbols_test.go", "repo_id": "tools", "token_count": 404 }
752
// 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" "fmt" "strings" "sync" "testing" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/test/integration/fake" "golang.org/x/tools/internal/jsonrpc2/servertest" ) // Env holds the building blocks of an editor testing environment, providing // wrapper methods that hide the boilerplate of plumbing contexts and checking // errors. type Env struct { T testing.TB // TODO(rfindley): rename to TB Ctx context.Context // Most tests should not need to access the scratch area, editor, server, or // connection, but they are available if needed. Sandbox *fake.Sandbox Server servertest.Connector // Editor is owned by the Env, and shut down Editor *fake.Editor Awaiter *Awaiter } // An Awaiter keeps track of relevant LSP state, so that it may be asserted // upon with Expectations. // // Wire it into a fake.Editor using Awaiter.Hooks(). // // TODO(rfindley): consider simply merging Awaiter with the fake.Editor. It // probably is not worth its own abstraction. type Awaiter struct { workdir *fake.Workdir mu sync.Mutex // For simplicity, each waiter gets a unique ID. nextWaiterID int state State waiters map[int]*condition } func NewAwaiter(workdir *fake.Workdir) *Awaiter { return &Awaiter{ workdir: workdir, state: State{ diagnostics: make(map[string]*protocol.PublishDiagnosticsParams), work: make(map[protocol.ProgressToken]*workProgress), startedWork: make(map[string]uint64), completedWork: make(map[string]uint64), }, waiters: make(map[int]*condition), } } // Hooks returns LSP client hooks required for awaiting asynchronous expectations. func (a *Awaiter) Hooks() fake.ClientHooks { return fake.ClientHooks{ OnDiagnostics: a.onDiagnostics, OnLogMessage: a.onLogMessage, OnWorkDoneProgressCreate: a.onWorkDoneProgressCreate, OnProgress: a.onProgress, OnShowDocument: a.onShowDocument, OnShowMessage: a.onShowMessage, OnShowMessageRequest: a.onShowMessageRequest, OnRegisterCapability: a.onRegisterCapability, OnUnregisterCapability: a.onUnregisterCapability, } } // ResetShownDocuments resets the set of accumulated ShownDocuments seen so far. func (a *Awaiter) ResetShownDocuments() { a.state.showDocument = nil } // State encapsulates the server state TODO: explain more type State struct { // diagnostics are a map of relative path->diagnostics params diagnostics map[string]*protocol.PublishDiagnosticsParams logs []*protocol.LogMessageParams showDocument []*protocol.ShowDocumentParams showMessage []*protocol.ShowMessageParams showMessageRequest []*protocol.ShowMessageRequestParams registrations []*protocol.RegistrationParams registeredCapabilities map[string]protocol.Registration unregistrations []*protocol.UnregistrationParams // outstandingWork is a map of token->work summary. All tokens are assumed to // be string, though the spec allows for numeric tokens as well. work map[protocol.ProgressToken]*workProgress startedWork map[string]uint64 // title -> count of 'begin' completedWork map[string]uint64 // title -> count of 'end' } type workProgress struct { title, msg, endMsg string percent float64 complete bool // seen 'end' } // This method, provided for debugging, accesses mutable fields without a lock, // so it must not be called concurrent with any State mutation. func (s State) String() string { var b strings.Builder b.WriteString("#### log messages (see RPC logs for full text):\n") for _, msg := range s.logs { summary := fmt.Sprintf("%v: %q", msg.Type, msg.Message) if len(summary) > 60 { summary = summary[:57] + "..." } // Some logs are quite long, and since they should be reproduced in the RPC // logs on any failure we include here just a short summary. fmt.Fprint(&b, "\t"+summary+"\n") } b.WriteString("\n") b.WriteString("#### diagnostics:\n") for name, params := range s.diagnostics { fmt.Fprintf(&b, "\t%s (version %d):\n", name, params.Version) for _, d := range params.Diagnostics { fmt.Fprintf(&b, "\t\t%d:%d [%s]: %s\n", d.Range.Start.Line, d.Range.Start.Character, d.Source, d.Message) } } b.WriteString("\n") b.WriteString("#### outstanding work:\n") for token, state := range s.work { if state.complete { continue } name := state.title if name == "" { name = fmt.Sprintf("!NO NAME(token: %s)", token) } fmt.Fprintf(&b, "\t%s: %.2f\n", name, state.percent) } b.WriteString("#### completed work:\n") for name, count := range s.completedWork { fmt.Fprintf(&b, "\t%s: %d\n", name, count) } return b.String() } // A condition is satisfied when all expectations are simultaneously // met. At that point, the 'met' channel is closed. On any failure, err is set // and the failed channel is closed. type condition struct { expectations []Expectation verdict chan Verdict } func (a *Awaiter) onDiagnostics(_ context.Context, d *protocol.PublishDiagnosticsParams) error { a.mu.Lock() defer a.mu.Unlock() pth := a.workdir.URIToPath(d.URI) a.state.diagnostics[pth] = d a.checkConditionsLocked() return nil } func (a *Awaiter) onShowDocument(_ context.Context, params *protocol.ShowDocumentParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.showDocument = append(a.state.showDocument, params) a.checkConditionsLocked() return nil } func (a *Awaiter) onShowMessage(_ context.Context, m *protocol.ShowMessageParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.showMessage = append(a.state.showMessage, m) a.checkConditionsLocked() return nil } func (a *Awaiter) onShowMessageRequest(_ context.Context, m *protocol.ShowMessageRequestParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.showMessageRequest = append(a.state.showMessageRequest, m) a.checkConditionsLocked() return nil } func (a *Awaiter) onLogMessage(_ context.Context, m *protocol.LogMessageParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.logs = append(a.state.logs, m) a.checkConditionsLocked() return nil } func (a *Awaiter) onWorkDoneProgressCreate(_ context.Context, m *protocol.WorkDoneProgressCreateParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.work[m.Token] = &workProgress{} return nil } func (a *Awaiter) onProgress(_ context.Context, m *protocol.ProgressParams) error { a.mu.Lock() defer a.mu.Unlock() work, ok := a.state.work[m.Token] if !ok { panic(fmt.Sprintf("got progress report for unknown report %v: %v", m.Token, m)) } v := m.Value.(map[string]interface{}) switch kind := v["kind"]; kind { case "begin": work.title = v["title"].(string) a.state.startedWork[work.title]++ if msg, ok := v["message"]; ok { work.msg = msg.(string) } case "report": if pct, ok := v["percentage"]; ok { work.percent = pct.(float64) } if msg, ok := v["message"]; ok { work.msg = msg.(string) } case "end": work.complete = true a.state.completedWork[work.title]++ if msg, ok := v["message"]; ok { work.endMsg = msg.(string) } } a.checkConditionsLocked() return nil } func (a *Awaiter) onRegisterCapability(_ context.Context, m *protocol.RegistrationParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.registrations = append(a.state.registrations, m) if a.state.registeredCapabilities == nil { a.state.registeredCapabilities = make(map[string]protocol.Registration) } for _, reg := range m.Registrations { a.state.registeredCapabilities[reg.Method] = reg } a.checkConditionsLocked() return nil } func (a *Awaiter) onUnregisterCapability(_ context.Context, m *protocol.UnregistrationParams) error { a.mu.Lock() defer a.mu.Unlock() a.state.unregistrations = append(a.state.unregistrations, m) a.checkConditionsLocked() return nil } func (a *Awaiter) checkConditionsLocked() { for id, condition := range a.waiters { if v, _ := checkExpectations(a.state, condition.expectations); v != Unmet { delete(a.waiters, id) condition.verdict <- v } } } // checkExpectations reports whether s meets all expectations. func checkExpectations(s State, expectations []Expectation) (Verdict, string) { finalVerdict := Met var summary strings.Builder for _, e := range expectations { v := e.Check(s) if v > finalVerdict { finalVerdict = v } fmt.Fprintf(&summary, "%v: %s\n", v, e.Description) } return finalVerdict, summary.String() } // Await blocks until the given expectations are all simultaneously met. // // Generally speaking Await should be avoided because it blocks indefinitely if // gopls ends up in a state where the expectations are never going to be met. // Use AfterChange or OnceMet instead, so that the runner knows when to stop // waiting. func (e *Env) Await(expectations ...Expectation) { e.T.Helper() if err := e.Awaiter.Await(e.Ctx, expectations...); err != nil { e.T.Fatal(err) } } // OnceMet blocks until the precondition is met by the state or becomes // unmeetable. If it was met, OnceMet checks that the state meets all // expectations in mustMeets. func (e *Env) OnceMet(precondition Expectation, mustMeets ...Expectation) { e.T.Helper() e.Await(OnceMet(precondition, mustMeets...)) } // Await waits for all expectations to simultaneously be met. It should only be // called from the main test goroutine. func (a *Awaiter) Await(ctx context.Context, expectations ...Expectation) error { a.mu.Lock() // Before adding the waiter, we check if the condition is currently met or // failed to avoid a race where the condition was realized before Await was // called. switch verdict, summary := checkExpectations(a.state, expectations); verdict { case Met: a.mu.Unlock() return nil case Unmeetable: err := fmt.Errorf("unmeetable expectations:\n%s\nstate:\n%v", summary, a.state) a.mu.Unlock() return err } cond := &condition{ expectations: expectations, verdict: make(chan Verdict), } a.waiters[a.nextWaiterID] = cond a.nextWaiterID++ a.mu.Unlock() var err error select { case <-ctx.Done(): err = ctx.Err() case v := <-cond.verdict: if v != Met { err = fmt.Errorf("condition has final verdict %v", v) } } a.mu.Lock() defer a.mu.Unlock() _, summary := checkExpectations(a.state, expectations) // Debugging an unmet expectation can be tricky, so we put some effort into // nicely formatting the failure. if err != nil { return fmt.Errorf("waiting on:\n%s\nerr:%v\n\nstate:\n%v", summary, err, a.state) } return nil }
tools/gopls/internal/test/integration/env.go/0
{ "file_path": "tools/gopls/internal/test/integration/env.go", "repo_id": "tools", "token_count": 3897 }
753
// 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 inlayhint import ( "os" "testing" "golang.org/x/tools/gopls/internal/settings" . "golang.org/x/tools/gopls/internal/test/integration" "golang.org/x/tools/gopls/internal/util/bug" ) func TestMain(m *testing.M) { bug.PanicOnBugs = true os.Exit(Main(m)) } func TestEnablingInlayHints(t *testing.T) { const workspace = ` -- go.mod -- module inlayHint.test go 1.12 -- lib.go -- package lib type Number int const ( Zero Number = iota One Two ) ` tests := []struct { label string enabled map[string]bool wantInlayHint bool }{ { label: "default", wantInlayHint: false, }, { label: "enable const", enabled: map[string]bool{string(settings.ConstantValues): true}, wantInlayHint: true, }, { label: "enable parameter names", enabled: map[string]bool{string(settings.ParameterNames): true}, wantInlayHint: false, }, } for _, test := range tests { t.Run(test.label, func(t *testing.T) { WithOptions( Settings{ "hints": test.enabled, }, ).Run(t, workspace, func(t *testing.T, env *Env) { env.OpenFile("lib.go") lens := env.InlayHints("lib.go") if gotInlayHint := len(lens) > 0; gotInlayHint != test.wantInlayHint { t.Errorf("got inlayHint: %t, want %t", gotInlayHint, test.wantInlayHint) } }) }) } }
tools/gopls/internal/test/integration/inlayhints/inlayhints_test.go/0
{ "file_path": "tools/gopls/internal/test/integration/inlayhints/inlayhints_test.go", "repo_id": "tools", "token_count": 676 }
754
// 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 misc import ( "strings" "testing" . "golang.org/x/tools/gopls/internal/test/integration" ) func TestHoverAndDocumentLink(t *testing.T) { const program = ` -- go.mod -- module mod.test go 1.12 require import.test v1.2.3 -- main.go -- package main import "import.test/pkg" func main() { // Issue 43990: this is not a link that most users can open from an LSP // client: mongodb://not.a.link.com println(pkg.Hello) }` const proxy = ` -- import.test@v1.2.3/go.mod -- module import.test go 1.12 -- import.test@v1.2.3/pkg/const.go -- package pkg const Hello = "Hello" ` WithOptions( ProxyFiles(proxy), WriteGoSum("."), ).Run(t, program, func(t *testing.T, env *Env) { env.OpenFile("main.go") env.OpenFile("go.mod") modLink := "https://pkg.go.dev/mod/import.test@v1.2.3" pkgLink := "https://pkg.go.dev/import.test@v1.2.3/pkg" // First, check that we get the expected links via hover and documentLink. content, _ := env.Hover(env.RegexpSearch("main.go", "pkg.Hello")) if content == nil || !strings.Contains(content.Value, pkgLink) { t.Errorf("hover: got %v in main.go, want contains %q", content, pkgLink) } content, _ = env.Hover(env.RegexpSearch("go.mod", "import.test")) if content == nil || !strings.Contains(content.Value, pkgLink) { t.Errorf("hover: got %v in go.mod, want contains %q", content, pkgLink) } links := env.DocumentLink("main.go") if len(links) != 1 || *links[0].Target != pkgLink { t.Errorf("documentLink: got links %+v for main.go, want one link with target %q", links, pkgLink) } links = env.DocumentLink("go.mod") if len(links) != 1 || *links[0].Target != modLink { t.Errorf("documentLink: got links %+v for go.mod, want one link with target %q", links, modLink) } // Then change the environment to make these links private. cfg := env.Editor.Config() cfg.Env = map[string]string{"GOPRIVATE": "import.test"} env.ChangeConfiguration(cfg) // Finally, verify that the links are gone. content, _ = env.Hover(env.RegexpSearch("main.go", "pkg.Hello")) if content == nil || strings.Contains(content.Value, pkgLink) { t.Errorf("hover: got %v in main.go, want non-empty hover without %q", content, pkgLink) } content, _ = env.Hover(env.RegexpSearch("go.mod", "import.test")) if content == nil || strings.Contains(content.Value, modLink) { t.Errorf("hover: got %v in go.mod, want contains %q", content, modLink) } links = env.DocumentLink("main.go") if len(links) != 0 { t.Errorf("documentLink: got %d document links for main.go, want 0\nlinks: %v", len(links), links) } links = env.DocumentLink("go.mod") if len(links) != 0 { t.Errorf("documentLink: got %d document links for go.mod, want 0\nlinks: %v", len(links), links) } }) }
tools/gopls/internal/test/integration/misc/link_test.go/0
{ "file_path": "tools/gopls/internal/test/integration/misc/link_test.go", "repo_id": "tools", "token_count": 1121 }
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. package modfile import ( "testing" . "golang.org/x/tools/gopls/internal/test/integration" ) // This test replaces an older, problematic test (golang/go#57784). But it has // been a long time since the go command would mutate go.mod files. // // TODO(golang/go#61970): the tempModfile setting should be removed entirely. func TestTempModfileUnchanged(t *testing.T) { // badMod has a go.mod file that is missing a go directive. const badMod = ` -- go.mod -- module badmod.test/p -- p.go -- package p ` WithOptions( Modes(Default), // no reason to test this with a remote gopls ProxyFiles(workspaceProxy), Settings{ "tempModfile": true, }, ).Run(t, badMod, func(t *testing.T, env *Env) { env.OpenFile("p.go") env.AfterChange() want := "module badmod.test/p\n" got := env.ReadWorkspaceFile("go.mod") if got != want { t.Errorf("go.mod content:\n%s\nwant:\n%s", got, want) } }) }
tools/gopls/internal/test/integration/modfile/tempmodfile_test.go/0
{ "file_path": "tools/gopls/internal/test/integration/modfile/tempmodfile_test.go", "repo_id": "tools", "token_count": 393 }
756
// 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 workspace import ( "sort" "testing" "github.com/google/go-cmp/cmp" "golang.org/x/tools/gopls/internal/protocol" . "golang.org/x/tools/gopls/internal/test/integration" ) func TestStandaloneFiles(t *testing.T) { const files = ` -- go.mod -- module mod.test go 1.16 -- lib/lib.go -- package lib const K = 0 type I interface { M() } -- lib/ignore.go -- //go:build ignore // +build ignore package main import ( "mod.test/lib" ) const K = 1 type Mer struct{} func (Mer) M() func main() { println(lib.K + K) } ` WithOptions( // On Go 1.17 and earlier, this test fails with // experimentalWorkspaceModule. Not investigated, as // experimentalWorkspaceModule will be removed. Modes(Default), ).Run(t, files, func(t *testing.T, env *Env) { // Initially, gopls should not know about the standalone file as it hasn't // been opened. Therefore, we should only find one symbol 'K'. // // (The choice of "K" is a little sleazy: it was originally "C" until // we started adding "unsafe" to the workspace unconditionally, which // caused a spurious match of "unsafe.Slice". But in practice every // workspace depends on unsafe.) syms := env.Symbol("K") if got, want := len(syms), 1; got != want { t.Errorf("got %d symbols, want %d (%+v)", got, want, syms) } // Similarly, we should only find one reference to "K", and no // implementations of I. checkLocations := func(method string, gotLocations []protocol.Location, wantFiles ...string) { var gotFiles []string for _, l := range gotLocations { gotFiles = append(gotFiles, env.Sandbox.Workdir.URIToPath(l.URI)) } sort.Strings(gotFiles) sort.Strings(wantFiles) if diff := cmp.Diff(wantFiles, gotFiles); diff != "" { t.Errorf("%s(...): unexpected locations (-want +got):\n%s", method, diff) } } env.OpenFile("lib/lib.go") env.AfterChange(NoDiagnostics()) // Replacing K with D should not cause any workspace diagnostics, since we // haven't yet opened the standalone file. env.RegexpReplace("lib/lib.go", "K", "D") env.AfterChange(NoDiagnostics()) env.RegexpReplace("lib/lib.go", "D", "K") env.AfterChange(NoDiagnostics()) refs := env.References(env.RegexpSearch("lib/lib.go", "K")) checkLocations("References", refs, "lib/lib.go") impls := env.Implementations(env.RegexpSearch("lib/lib.go", "I")) checkLocations("Implementations", impls) // no implementations // Opening the standalone file should not result in any diagnostics. env.OpenFile("lib/ignore.go") env.AfterChange(NoDiagnostics()) // Having opened the standalone file, we should find its symbols in the // workspace. syms = env.Symbol("K") if got, want := len(syms), 2; got != want { t.Fatalf("got %d symbols, want %d", got, want) } foundMainK := false var symNames []string for _, sym := range syms { symNames = append(symNames, sym.Name) if sym.Name == "main.K" { foundMainK = true } } if !foundMainK { t.Errorf("WorkspaceSymbol(\"K\") = %v, want containing main.K", symNames) } // We should resolve workspace definitions in the standalone file. fileLoc := env.GoToDefinition(env.RegexpSearch("lib/ignore.go", "lib.(K)")) file := env.Sandbox.Workdir.URIToPath(fileLoc.URI) if got, want := file, "lib/lib.go"; got != want { t.Errorf("GoToDefinition(lib.K) = %v, want %v", got, want) } // ...as well as intra-file definitions loc := env.GoToDefinition(env.RegexpSearch("lib/ignore.go", "\\+ (K)")) wantLoc := env.RegexpSearch("lib/ignore.go", "const (K)") if loc != wantLoc { t.Errorf("GoToDefinition(K) = %v, want %v", loc, wantLoc) } // Renaming "lib.K" to "lib.D" should cause a diagnostic in the standalone // file. env.RegexpReplace("lib/lib.go", "K", "D") env.AfterChange(Diagnostics(env.AtRegexp("lib/ignore.go", "lib.(K)"))) // Undoing the replacement should fix diagnostics env.RegexpReplace("lib/lib.go", "D", "K") env.AfterChange(NoDiagnostics()) // Now that our workspace has no errors, we should be able to find // references and rename. refs = env.References(env.RegexpSearch("lib/lib.go", "K")) checkLocations("References", refs, "lib/lib.go", "lib/ignore.go") impls = env.Implementations(env.RegexpSearch("lib/lib.go", "I")) checkLocations("Implementations", impls, "lib/ignore.go") // Renaming should rename in the standalone package. env.Rename(env.RegexpSearch("lib/lib.go", "K"), "D") env.RegexpSearch("lib/ignore.go", "lib.D") }) } func TestStandaloneFiles_Configuration(t *testing.T) { const files = ` -- go.mod -- module mod.test go 1.18 -- lib.go -- package lib // without this package, files are loaded as command-line-arguments -- ignore.go -- //go:build ignore // +build ignore package main // An arbitrary comment. func main() {} -- standalone.go -- //go:build standalone // +build standalone package main func main() {} ` WithOptions( Settings{ "standaloneTags": []string{"standalone", "script"}, }, ).Run(t, files, func(t *testing.T, env *Env) { env.OpenFile("ignore.go") env.OpenFile("standalone.go") env.AfterChange( Diagnostics(env.AtRegexp("ignore.go", "package (main)")), NoDiagnostics(ForFile("standalone.go")), ) cfg := env.Editor.Config() cfg.Settings = map[string]interface{}{ "standaloneTags": []string{"ignore"}, } env.ChangeConfiguration(cfg) env.AfterChange( NoDiagnostics(ForFile("ignore.go")), Diagnostics(env.AtRegexp("standalone.go", "package (main)")), ) }) }
tools/gopls/internal/test/integration/workspace/standalone_test.go/0
{ "file_path": "tools/gopls/internal/test/integration/workspace/standalone_test.go", "repo_id": "tools", "token_count": 2119 }
757
// 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 goversions defines gopls's policy for which versions of Go it supports. package goversion import ( "fmt" "strings" ) // Support holds information about end-of-life Go version support. // // Exposed for testing. type Support struct { // GoVersion is the Go version to which these settings relate. GoVersion int // DeprecatedVersion is the first version of gopls that no longer supports // this Go version. // // If unset, the version is already deprecated. DeprecatedVersion string // InstallGoplsVersion is the latest gopls version that supports this Go // version without warnings. InstallGoplsVersion string } // Supported maps Go versions to the gopls version in which support will // be deprecated, and the final gopls version supporting them without warnings. // Keep this in sync with gopls/README.md. // // Must be sorted in ascending order of Go version. // // Exposed (and mutable) for testing. var Supported = []Support{ {12, "", "v0.7.5"}, {15, "", "v0.9.5"}, {16, "", "v0.11.0"}, {17, "", "v0.11.0"}, {18, "", "v0.14.2"}, {19, "v0.17.0", "v0.15.3"}, {20, "v0.17.0", "v0.15.3"}, } // OldestSupported is the last X in Go 1.X that this version of gopls // supports without warnings. // // Exported for testing. func OldestSupported() int { return Supported[len(Supported)-1].GoVersion + 1 } // Message returns the message to display if the user has the given Go // version, if any. The goVersion variable is the X in Go 1.X. If // fromBuild is set, the Go version is the version used to build // gopls. Otherwise, it is the go command version. // // The second component of the result indicates whether the message is // an error, not a mere warning. // // If goVersion is invalid (< 0), it returns "", false. func Message(goVersion int, fromBuild bool) (string, bool) { if goVersion < 0 { return "", false } for _, v := range Supported { if goVersion <= v.GoVersion { var msgBuilder strings.Builder isError := true if fromBuild { fmt.Fprintf(&msgBuilder, "Gopls was built with Go version 1.%d", goVersion) } else { fmt.Fprintf(&msgBuilder, "Found Go version 1.%d", goVersion) } if v.DeprecatedVersion != "" { // not deprecated yet, just a warning fmt.Fprintf(&msgBuilder, ", which will be unsupported by gopls %s. ", v.DeprecatedVersion) isError = false // warning } else { fmt.Fprint(&msgBuilder, ", which is not supported by this version of gopls. ") } fmt.Fprintf(&msgBuilder, "Please upgrade to Go 1.%d or later and reinstall gopls. ", OldestSupported()) fmt.Fprintf(&msgBuilder, "If you can't upgrade and want this message to go away, please install gopls %s. ", v.InstallGoplsVersion) fmt.Fprint(&msgBuilder, "See https://go.dev/s/gopls-support-policy for more details.") return msgBuilder.String(), isError } } return "", false }
tools/gopls/internal/util/goversion/goversion.go/0
{ "file_path": "tools/gopls/internal/util/goversion/goversion.go", "repo_id": "tools", "token_count": 997 }
758
// 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 version manages the gopls version. // // The VersionOverride variable may be used to set the gopls version at link // time. package version import "runtime/debug" var VersionOverride = "" // Version returns the gopls version. // // By default, this is read from runtime/debug.ReadBuildInfo, but may be // overridden by the [VersionOverride] variable. func Version() string { if VersionOverride != "" { return VersionOverride } if info, ok := debug.ReadBuildInfo(); ok { if info.Main.Version != "" { return info.Main.Version } } return "(unknown)" }
tools/gopls/internal/version/version.go/0
{ "file_path": "tools/gopls/internal/version/version.go", "repo_id": "tools", "token_count": 214 }
759
{ "id": "GO-2020-0001", "modified": "0001-01-01T00:00:00Z", "published": "0001-01-01T00:00:00Z", "details": "The default Formatter for the Logger middleware (LoggerConfig.Formatter),\nwhich is included in the Default engine, allows attackers to inject arbitrary\nlog entries by manipulating the request path.\n", "affected": [ { "package": { "name": "github.com/gin-gonic/gin", "ecosystem": "Go" }, "ranges": [ { "type": "SEMVER", "events": [ { "introduced": "0" }, { "fixed": "1.6.0" } ] } ], "ecosystem_specific": { "imports": [ { "path": "github.com/gin-gonic/gin", "symbols": [ "defaultLogFormatter" ] } ] } } ], "references": [ { "type": "FIX", "url": "https://github.com/gin-gonic/gin/pull/1234" }, { "type": "FIX", "url": "https://github.com/gin-gonic/gin/commit/abcdefg" } ], "database_specific": { "url": "https://pkg.go.dev/vuln/GO-2020-0001" } }
tools/gopls/internal/vulncheck/vulntest/testdata/GO-2020-0001.json/0
{ "file_path": "tools/gopls/internal/vulncheck/vulntest/testdata/GO-2020-0001.json", "repo_id": "tools", "token_count": 529 }
760
// 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 analysisinternal_test import ( "testing" "golang.org/x/tools/internal/analysisinternal" ) func TestExtractDoc(t *testing.T) { const multi = `// Copyright //+build tag // Package foo // // # Irrelevant heading // // This is irrelevant doc. // // # Analyzer nocolon // // This one has the wrong form for this line. // // # Analyzer food // // food: reports dining opportunities // // This is the doc for analyzer 'food'. // // # Analyzer foo // // foo: reports diagnostics // // This is the doc for analyzer 'foo'. // // # Analyzer bar // // bar: reports drinking opportunities // // This is the doc for analyzer 'bar'. package blah var x = syntax error ` for _, test := range []struct { content, name string want string // doc or "error: %w" string }{ {"", "foo", "error: empty Go source file"}, {"//foo", "foo", "error: not a Go source file"}, {"//foo\npackage foo", "foo", "error: package doc comment contains no 'Analyzer foo' heading"}, {multi, "foo", "reports diagnostics\n\nThis is the doc for analyzer 'foo'."}, {multi, "bar", "reports drinking opportunities\n\nThis is the doc for analyzer 'bar'."}, {multi, "food", "reports dining opportunities\n\nThis is the doc for analyzer 'food'."}, {multi, "nope", "error: package doc comment contains no 'Analyzer nope' heading"}, {multi, "nocolon", "error: 'Analyzer nocolon' heading not followed by 'nocolon: summary...' line"}, } { got, err := analysisinternal.ExtractDoc(test.content, test.name) if err != nil { got = "error: " + err.Error() } if test.want != got { t.Errorf("ExtractDoc(%q) returned <<%s>>, want <<%s>>, given input <<%s>>", test.name, got, test.want, test.content) } } }
tools/internal/analysisinternal/extractdoc_test.go/0
{ "file_path": "tools/internal/analysisinternal/extractdoc_test.go", "repo_id": "tools", "token_count": 669 }
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 difftest supplies a set of tests that will operate on any // implementation of a diff algorithm as exposed by // "golang.org/x/tools/internal/diff" package difftest_test import ( "fmt" "os" "os/exec" "strings" "testing" "golang.org/x/tools/internal/diff/difftest" "golang.org/x/tools/internal/testenv" ) func TestVerifyUnified(t *testing.T) { testenv.NeedsTool(t, "diff") for _, test := range difftest.TestCases { t.Run(test.Name, func(t *testing.T) { if test.NoDiff { t.Skip("diff tool produces expected different results") } diff, err := getDiffOutput(test.In, test.Out) if err != nil { t.Fatal(err) } if len(diff) > 0 { diff = difftest.UnifiedPrefix + diff } if diff != test.Unified { t.Errorf("unified:\n%s\ndiff -u:\n%s", test.Unified, diff) } }) } } func getDiffOutput(a, b string) (string, error) { fileA, err := os.CreateTemp("", "myers.in") if err != nil { return "", err } defer os.Remove(fileA.Name()) if _, err := fileA.Write([]byte(a)); err != nil { return "", err } if err := fileA.Close(); err != nil { return "", err } fileB, err := os.CreateTemp("", "myers.in") if err != nil { return "", err } defer os.Remove(fileB.Name()) if _, err := fileB.Write([]byte(b)); err != nil { return "", err } if err := fileB.Close(); err != nil { return "", err } cmd := exec.Command("diff", "-u", fileA.Name(), fileB.Name()) cmd.Env = append(cmd.Env, "LANG=en_US.UTF-8") out, err := cmd.Output() if err != nil { exit, ok := err.(*exec.ExitError) if !ok { return "", fmt.Errorf("can't exec %s: %v", cmd, err) } if len(out) == 0 { // Nonzero exit with no output: terminated by signal? return "", fmt.Errorf("%s failed: %v; stderr:\n%s", cmd, err, exit.Stderr) } // nonzero exit + output => files differ } diff := string(out) if len(diff) <= 0 { return diff, nil } bits := strings.SplitN(diff, "\n", 3) if len(bits) != 3 { return "", fmt.Errorf("diff output did not have file prefix:\n%s", diff) } return bits[2], nil }
tools/internal/diff/difftest/difftest_test.go/0
{ "file_path": "tools/internal/diff/difftest/difftest_test.go", "repo_id": "tools", "token_count": 923 }
762
// 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 event_test import ( "context" "io" "log" "testing" "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/keys" "golang.org/x/tools/internal/event/label" ) type Hooks struct { A func(ctx context.Context, a int) (context.Context, func()) B func(ctx context.Context, b string) (context.Context, func()) } var ( aValue = keys.NewInt("a", "") bValue = keys.NewString("b", "") aCount = keys.NewInt64("aCount", "Count of time A is called.") aStat = keys.NewInt("aValue", "A value.") bCount = keys.NewInt64("B", "Count of time B is called.") bLength = keys.NewInt("BLen", "B length.") Baseline = Hooks{ A: func(ctx context.Context, a int) (context.Context, func()) { return ctx, func() {} }, B: func(ctx context.Context, b string) (context.Context, func()) { return ctx, func() {} }, } StdLog = Hooks{ A: func(ctx context.Context, a int) (context.Context, func()) { log.Printf("A where a=%d", a) return ctx, func() {} }, B: func(ctx context.Context, b string) (context.Context, func()) { log.Printf("B where b=%q", b) return ctx, func() {} }, } Log = Hooks{ A: func(ctx context.Context, a int) (context.Context, func()) { core.Log1(ctx, "A", aValue.Of(a)) return ctx, func() {} }, B: func(ctx context.Context, b string) (context.Context, func()) { core.Log1(ctx, "B", bValue.Of(b)) return ctx, func() {} }, } Trace = Hooks{ A: func(ctx context.Context, a int) (context.Context, func()) { return core.Start1(ctx, "A", aValue.Of(a)) }, B: func(ctx context.Context, b string) (context.Context, func()) { return core.Start1(ctx, "B", bValue.Of(b)) }, } Stats = Hooks{ A: func(ctx context.Context, a int) (context.Context, func()) { core.Metric1(ctx, aStat.Of(a)) core.Metric1(ctx, aCount.Of(1)) return ctx, func() {} }, B: func(ctx context.Context, b string) (context.Context, func()) { core.Metric1(ctx, bLength.Of(len(b))) core.Metric1(ctx, bCount.Of(1)) return ctx, func() {} }, } initialList = []int{0, 1, 22, 333, 4444, 55555, 666666, 7777777} stringList = []string{ "A value", "Some other value", "A nice longer value but not too long", "V", "", "ı", "prime count of values", } ) type namedBenchmark struct { name string test func(*testing.B) } func Benchmark(b *testing.B) { b.Run("Baseline", Baseline.runBenchmark) b.Run("StdLog", StdLog.runBenchmark) benchmarks := []namedBenchmark{ {"Log", Log.runBenchmark}, {"Trace", Trace.runBenchmark}, {"Stats", Stats.runBenchmark}, } event.SetExporter(nil) for _, t := range benchmarks { b.Run(t.name+"NoExporter", t.test) } event.SetExporter(noopExporter) for _, t := range benchmarks { b.Run(t.name+"Noop", t.test) } event.SetExporter(export.Spans(export.LogWriter(io.Discard, false))) for _, t := range benchmarks { b.Run(t.name, t.test) } } func A(ctx context.Context, hooks Hooks, a int) int { ctx, done := hooks.A(ctx, a) defer done() return B(ctx, hooks, a, stringList[a%len(stringList)]) } func B(ctx context.Context, hooks Hooks, a int, b string) int { _, done := hooks.B(ctx, b) defer done() return a + len(b) } func (hooks Hooks) runBenchmark(b *testing.B) { ctx := context.Background() b.ReportAllocs() b.ResetTimer() var acc int for i := 0; i < b.N; i++ { for _, value := range initialList { acc += A(ctx, hooks, value) } } } func init() { log.SetOutput(io.Discard) } func noopExporter(ctx context.Context, ev core.Event, lm label.Map) context.Context { return ctx }
tools/internal/event/bench_test.go/0
{ "file_path": "tools/internal/event/bench_test.go", "repo_id": "tools", "token_count": 1574 }
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 ocagent_test import ( "context" "errors" "testing" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/event/keys" ) func TestEncodeMetric(t *testing.T) { exporter := registerExporter() const prefix = testNodeStr + ` "metrics":[` const suffix = `]}` tests := []struct { name string run func(ctx context.Context) want string }{ { name: "HistogramFloat64, HistogramInt64", run: func(ctx context.Context) { ctx = event.Label(ctx, keyMethod.Of("godoc.ServeHTTP")) event.Metric(ctx, latencyMs.Of(96.58)) ctx = event.Label(ctx, keys.Err.Of(errors.New("panic: fatal signal"))) event.Metric(ctx, bytesIn.Of(97e2)) }, want: prefix + ` { "metric_descriptor": { "name": "latency_ms", "description": "The latency of calls in milliseconds", "type": 6, "label_keys": [ { "key": "method" }, { "key": "route" } ] }, "timeseries": [ { "start_timestamp": "1970-01-01T00:00:00Z", "points": [ { "timestamp": "1970-01-01T00:00:40Z", "distributionValue": { "count": 1, "sum": 96.58, "bucket_options": { "explicit": { "bounds": [ 0, 5, 10, 25, 50 ] } }, "buckets": [ {}, {}, {}, {}, {} ] } } ] } ] }, { "metric_descriptor": { "name": "latency_ms", "description": "The latency of calls in milliseconds", "type": 6, "label_keys": [ { "key": "method" }, { "key": "route" } ] }, "timeseries": [ { "start_timestamp": "1970-01-01T00:00:00Z", "points": [ { "timestamp": "1970-01-01T00:00:40Z", "distributionValue": { "count": 1, "sum": 9700, "bucket_options": { "explicit": { "bounds": [ 0, 10, 50, 100, 500, 1000, 2000 ] } }, "buckets": [ {}, {}, {}, {}, {}, {}, {} ] } } ] } ] }` + suffix, }, } ctx := context.TODO() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.run(ctx) got := exporter.Output("/v1/metrics") checkJSON(t, got, []byte(tt.want)) }) } }
tools/internal/event/export/ocagent/metrics_test.go/0
{ "file_path": "tools/internal/event/export/ocagent/metrics_test.go", "repo_id": "tools", "token_count": 1657 }
764
// 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 label import ( "fmt" "io" "reflect" "unsafe" ) // Key is used as the identity of a Label. // Keys are intended to be compared by pointer only, the name should be unique // for communicating with external systems, but it is not required or enforced. type Key interface { // Name returns the key name. Name() string // Description returns a string that can be used to describe the value. Description() string // Format is used in formatting to append the value of the label to the // supplied buffer. // The formatter may use the supplied buf as a scratch area to avoid // allocations. Format(w io.Writer, buf []byte, l Label) } // Label holds a key and value pair. // It is normally used when passing around lists of labels. type Label struct { key Key packed uint64 untyped interface{} } // Map is the interface to a collection of Labels indexed by key. type Map interface { // Find returns the label that matches the supplied key. Find(key Key) Label } // List is the interface to something that provides an iterable // list of labels. // Iteration should start from 0 and continue until Valid returns false. type List interface { // Valid returns true if the index is within range for the list. // It does not imply the label at that index will itself be valid. Valid(index int) bool // Label returns the label at the given index. Label(index int) Label } // list implements LabelList for a list of Labels. type list struct { labels []Label } // filter wraps a LabelList filtering out specific labels. type filter struct { keys []Key underlying List } // listMap implements LabelMap for a simple list of labels. type listMap struct { labels []Label } // mapChain implements LabelMap for a list of underlying LabelMap. type mapChain struct { maps []Map } // OfValue creates a new label from the key and value. // This method is for implementing new key types, label creation should // normally be done with the Of method of the key. func OfValue(k Key, value interface{}) Label { return Label{key: k, untyped: value} } // UnpackValue assumes the label was built using LabelOfValue and returns the value // that was passed to that constructor. // This method is for implementing new key types, for type safety normal // access should be done with the From method of the key. func (t Label) UnpackValue() interface{} { return t.untyped } // Of64 creates a new label from a key and a uint64. This is often // used for non uint64 values that can be packed into a uint64. // This method is for implementing new key types, label creation should // normally be done with the Of method of the key. func Of64(k Key, v uint64) Label { return Label{key: k, packed: v} } // Unpack64 assumes the label was built using LabelOf64 and returns the value that // was passed to that constructor. // This method is for implementing new key types, for type safety normal // access should be done with the From method of the key. func (t Label) Unpack64() uint64 { return t.packed } type stringptr unsafe.Pointer // OfString creates a new label from a key and a string. // This method is for implementing new key types, label creation should // normally be done with the Of method of the key. func OfString(k Key, v string) Label { hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) return Label{ key: k, packed: uint64(hdr.Len), untyped: stringptr(hdr.Data), } } // UnpackString assumes the label was built using LabelOfString and returns the // value that was passed to that constructor. // This method is for implementing new key types, for type safety normal // access should be done with the From method of the key. func (t Label) UnpackString() string { var v string hdr := (*reflect.StringHeader)(unsafe.Pointer(&v)) hdr.Data = uintptr(t.untyped.(stringptr)) hdr.Len = int(t.packed) return v } // Valid returns true if the Label is a valid one (it has a key). func (t Label) Valid() bool { return t.key != nil } // Key returns the key of this Label. func (t Label) Key() Key { return t.key } // Format is used for debug printing of labels. func (t Label) Format(f fmt.State, r rune) { if !t.Valid() { io.WriteString(f, `nil`) return } io.WriteString(f, t.Key().Name()) io.WriteString(f, "=") var buf [128]byte t.Key().Format(f, buf[:0], t) } func (l *list) Valid(index int) bool { return index >= 0 && index < len(l.labels) } func (l *list) Label(index int) Label { return l.labels[index] } func (f *filter) Valid(index int) bool { return f.underlying.Valid(index) } func (f *filter) Label(index int) Label { l := f.underlying.Label(index) for _, f := range f.keys { if l.Key() == f { return Label{} } } return l } func (lm listMap) Find(key Key) Label { for _, l := range lm.labels { if l.Key() == key { return l } } return Label{} } func (c mapChain) Find(key Key) Label { for _, src := range c.maps { l := src.Find(key) if l.Valid() { return l } } return Label{} } var emptyList = &list{} func NewList(labels ...Label) List { if len(labels) == 0 { return emptyList } return &list{labels: labels} } func Filter(l List, keys ...Key) List { if len(keys) == 0 { return l } return &filter{keys: keys, underlying: l} } func NewMap(labels ...Label) Map { return listMap{labels: labels} } func MergeMaps(srcs ...Map) Map { var nonNil []Map for _, src := range srcs { if src != nil { nonNil = append(nonNil, src) } } if len(nonNil) == 1 { return nonNil[0] } return mapChain{maps: nonNil} }
tools/internal/event/label/label.go/0
{ "file_path": "tools/internal/event/label/label.go", "repo_id": "tools", "token_count": 1819 }
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 gocommand_test import ( "context" "testing" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/testenv" ) func TestGoVersion(t *testing.T) { testenv.NeedsTool(t, "go") inv := gocommand.Invocation{ Verb: "version", } gocmdRunner := &gocommand.Runner{} if _, err := gocmdRunner.Run(context.Background(), inv); err != nil { t.Error(err) } }
tools/internal/gocommand/invoke_test.go/0
{ "file_path": "tools/internal/gocommand/invoke_test.go", "repo_id": "tools", "token_count": 209 }
766
// 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 imports import ( "archive/zip" "context" "fmt" "log" "os" "path/filepath" "reflect" "regexp" "sort" "strings" "sync" "testing" "time" "golang.org/x/mod/module" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/gopathwalk" "golang.org/x/tools/internal/proxydir" "golang.org/x/tools/internal/testenv" "golang.org/x/tools/txtar" ) // Tests that we can find packages in the stdlib. func TestScanStdlib(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x `, "") defer mt.cleanup() mt.assertScanFinds("fmt", "fmt") } // Tests that we handle a nested module. This is different from other tests // where the module is in scope -- here we have to figure out the import path // without any help from go list. func TestScanOutOfScopeNestedModule(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x -- x.go -- package x -- v2/go.mod -- module x -- v2/x.go -- package x`, "") defer mt.cleanup() pkg := mt.assertScanFinds("x/v2", "x") if pkg != nil && !strings.HasSuffix(filepath.ToSlash(pkg.dir), "main/v2") { t.Errorf("x/v2 was found in %v, wanted .../main/v2", pkg.dir) } // We can't load the package name from the import path, but that should // be okay -- if we end up adding this result, we'll add it with a name // if necessary. } // Tests that we don't find a nested module contained in a local replace target. // The code for this case is too annoying to write, so it's just ignored. func TestScanNestedModuleInLocalReplace(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require y v0.0.0 replace y => ./y -- x.go -- package x -- y/go.mod -- module y -- y/y.go -- package y -- y/z/go.mod -- module y/z -- y/z/z.go -- package z `, "") defer mt.cleanup() mt.assertFound("y", "y") scan, err := scanToSlice(mt.env.resolver, nil) if err != nil { t.Fatal(err) } for _, pkg := range scan { if strings.HasSuffix(filepath.ToSlash(pkg.dir), "main/y/z") { t.Errorf("scan found a package %v in dir main/y/z, wanted none", pkg.importPathShort) } } } // Tests that path encoding is handled correctly. Adapted from mod_case.txt. func TestModCase(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require rsc.io/QUOTE v1.5.2 -- x.go -- package x import _ "rsc.io/QUOTE/QUOTE" `, "") defer mt.cleanup() mt.assertFound("rsc.io/QUOTE/QUOTE", "QUOTE") } // Not obviously relevant to goimports. Adapted from mod_domain_root.txt anyway. func TestModDomainRoot(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require example.com v1.0.0 -- x.go -- package x import _ "example.com" `, "") defer mt.cleanup() mt.assertFound("example.com", "x") } // Tests that scanning the module cache > 1 time is able to find the same module. func TestModMultipleScans(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require example.com v1.0.0 -- x.go -- package x import _ "example.com" `, "") defer mt.cleanup() mt.assertScanFinds("example.com", "x") mt.assertScanFinds("example.com", "x") } // Tests that scanning the module cache > 1 time is able to find the same module // in the module cache. func TestModMultipleScansWithSubdirs(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require rsc.io/quote v1.5.2 -- x.go -- package x import _ "rsc.io/quote" `, "") defer mt.cleanup() mt.assertScanFinds("rsc.io/quote", "quote") mt.assertScanFinds("rsc.io/quote", "quote") } // Tests that scanning the module cache > 1 after changing a package in module cache to make it unimportable // is able to find the same module. func TestModCacheEditModFile(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require rsc.io/quote v1.5.2 -- x.go -- package x import _ "rsc.io/quote" `, "") defer mt.cleanup() found := mt.assertScanFinds("rsc.io/quote", "quote") if found == nil { t.Fatal("rsc.io/quote not found in initial scan.") } // Update the go.mod file of example.com so that it changes its module path (not allowed). if err := os.Chmod(filepath.Join(found.dir, "go.mod"), 0644); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(found.dir, "go.mod"), []byte("module bad.com\n"), 0644); err != nil { t.Fatal(err) } // Test that with its cache of module packages it still finds the package. mt.assertScanFinds("rsc.io/quote", "quote") // Rewrite the main package so that rsc.io/quote is not in scope. if err := os.WriteFile(filepath.Join(mt.env.WorkingDir, "go.mod"), []byte("module x\n"), 0644); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(mt.env.WorkingDir, "x.go"), []byte("package x\n"), 0644); err != nil { t.Fatal(err) } // Uninitialize the go.mod dependent cached information and make sure it still finds the package. mt.env.ClearModuleInfo() mt.assertScanFinds("rsc.io/quote", "quote") } // Tests that -mod=vendor works. Adapted from mod_vendor_build.txt. func TestModVendorBuild(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module m go 1.12 require rsc.io/sampler v1.3.1 -- x.go -- package x import _ "rsc.io/sampler" `, "") defer mt.cleanup() // Sanity-check the setup. mt.assertModuleFoundInDir("rsc.io/sampler", "sampler", `pkg.*mod.*/sampler@.*$`) // Populate vendor/ and clear out the mod cache so we can't cheat. if _, err := mt.env.invokeGo(context.Background(), "mod", "vendor"); err != nil { t.Fatal(err) } if _, err := mt.env.invokeGo(context.Background(), "clean", "-modcache"); err != nil { t.Fatal(err) } // Clear out the resolver's cache, since we've changed the environment. mt.env.Env["GOFLAGS"] = "-mod=vendor" mt.env.ClearModuleInfo() mt.env.UpdateResolver(mt.env.resolver.ClearForNewScan()) mt.assertModuleFoundInDir("rsc.io/sampler", "sampler", `/vendor/`) } // Tests that -mod=vendor is auto-enabled only for go1.14 and higher. // Vaguely inspired by mod_vendor_auto.txt. func TestModVendorAuto(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module m go 1.14 require rsc.io/sampler v1.3.1 -- x.go -- package x import _ "rsc.io/sampler" `, "") defer mt.cleanup() // Populate vendor/. if _, err := mt.env.invokeGo(context.Background(), "mod", "vendor"); err != nil { t.Fatal(err) } wantDir := `pkg.*mod.*/sampler@.*$` if testenv.Go1Point() >= 14 { wantDir = `/vendor/` } // Clear out the resolver's module info, since we've changed the environment. // (the presence of a /vendor directory affects `go list -m`). mt.env.ClearModuleInfo() mt.assertModuleFoundInDir("rsc.io/sampler", "sampler", wantDir) } // Tests that a module replace works. Adapted from mod_list.txt. We start with // go.mod2; the first part of the test is irrelevant. func TestModList(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require rsc.io/quote v1.5.1 replace rsc.io/sampler v1.3.0 => rsc.io/sampler v1.3.1 -- x.go -- package x import _ "rsc.io/quote" `, "") defer mt.cleanup() mt.assertModuleFoundInDir("rsc.io/sampler", "sampler", `pkg.mod.*/sampler@v1.3.1$`) } // Tests that a local replace works. Adapted from mod_local_replace.txt. func TestModLocalReplace(t *testing.T) { mt := setup(t, nil, ` -- x/y/go.mod -- module x/y require zz v1.0.0 replace zz v1.0.0 => ../z -- x/y/y.go -- package y import _ "zz" -- x/z/go.mod -- module x/z -- x/z/z.go -- package z `, "x/y") defer mt.cleanup() mt.assertFound("zz", "z") } // Tests that the package at the root of the main module can be found. // Adapted from the first part of mod_multirepo.txt. func TestModMultirepo1(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module rsc.io/quote -- x.go -- package quote `, "") defer mt.cleanup() mt.assertModuleFoundInDir("rsc.io/quote", "quote", `/main`) } // Tests that a simple module dependency is found. Adapted from the third part // of mod_multirepo.txt (We skip the case where it doesn't have a go.mod // entry -- we just don't work in that case.) func TestModMultirepo3(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module rsc.io/quote require rsc.io/quote/v2 v2.0.1 -- x.go -- package quote import _ "rsc.io/quote/v2" `, "") defer mt.cleanup() mt.assertModuleFoundInDir("rsc.io/quote", "quote", `/main`) mt.assertModuleFoundInDir("rsc.io/quote/v2", "quote", `pkg.mod.*/v2@v2.0.1$`) } // Tests that a nested module is found in the module cache, even though // it's checked out. Adapted from the fourth part of mod_multirepo.txt. func TestModMultirepo4(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module rsc.io/quote require rsc.io/quote/v2 v2.0.1 -- x.go -- package quote import _ "rsc.io/quote/v2" -- v2/go.mod -- package rsc.io/quote/v2 -- v2/x.go -- package quote import _ "rsc.io/quote/v2" `, "") defer mt.cleanup() mt.assertModuleFoundInDir("rsc.io/quote", "quote", `/main`) mt.assertModuleFoundInDir("rsc.io/quote/v2", "quote", `pkg.mod.*/v2@v2.0.1$`) } // Tests a simple module dependency. Adapted from the first part of mod_replace.txt. func TestModReplace1(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module quoter require rsc.io/quote/v3 v3.0.0 -- main.go -- package main `, "") defer mt.cleanup() mt.assertFound("rsc.io/quote/v3", "quote") } // Tests a local replace. Adapted from the second part of mod_replace.txt. func TestModReplace2(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module quoter require rsc.io/quote/v3 v3.0.0 replace rsc.io/quote/v3 => ./local/rsc.io/quote/v3 -- main.go -- package main -- local/rsc.io/quote/v3/go.mod -- module rsc.io/quote/v3 require rsc.io/sampler v1.3.0 -- local/rsc.io/quote/v3/quote.go -- package quote import "rsc.io/sampler" `, "") defer mt.cleanup() mt.assertModuleFoundInDir("rsc.io/quote/v3", "quote", `/local/rsc.io/quote/v3`) } // Tests that a module can be replaced by a different module path. Adapted // from the third part of mod_replace.txt. func TestModReplace3(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module quoter require not-rsc.io/quote/v3 v3.1.0 replace not-rsc.io/quote/v3 v3.1.0 => ./local/rsc.io/quote/v3 -- usenewmodule/main.go -- package main -- local/rsc.io/quote/v3/go.mod -- module rsc.io/quote/v3 require rsc.io/sampler v1.3.0 -- local/rsc.io/quote/v3/quote.go -- package quote -- local/not-rsc.io/quote/v3/go.mod -- module not-rsc.io/quote/v3 -- local/not-rsc.io/quote/v3/quote.go -- package quote `, "") defer mt.cleanup() mt.assertModuleFoundInDir("not-rsc.io/quote/v3", "quote", "local/rsc.io/quote/v3") } // Tests more local replaces, notably the case where an outer module provides // a package that could also be provided by an inner module. Adapted from // mod_replace_import.txt, with example.com/v changed to /vv because Go 1.11 // thinks /v is an invalid major version. func TestModReplaceImport(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module example.com/m replace ( example.com/a => ./a example.com/a/b => ./b ) replace ( example.com/x => ./x example.com/x/v3 => ./v3 ) replace ( example.com/y/z/w => ./w example.com/y => ./y ) replace ( example.com/vv v1.11.0 => ./v11 example.com/vv v1.12.0 => ./v12 example.com/vv => ./vv ) require ( example.com/a/b v0.0.0 example.com/x/v3 v3.0.0 example.com/y v0.0.0 example.com/y/z/w v0.0.0 example.com/vv v1.12.0 ) -- m.go -- package main import ( _ "example.com/a/b" _ "example.com/x/v3" _ "example.com/y/z/w" _ "example.com/vv" ) func main() {} -- a/go.mod -- module a.localhost -- a/a.go -- package a -- a/b/b.go-- package b -- b/go.mod -- module a.localhost/b -- b/b.go -- package b -- x/go.mod -- module x.localhost -- x/x.go -- package x -- x/v3.go -- package v3 import _ "x.localhost/v3" -- v3/go.mod -- module x.localhost/v3 -- v3/x.go -- package x -- w/go.mod -- module w.localhost -- w/skip/skip.go -- // Package skip is nested below nonexistent package w. package skip -- y/go.mod -- module y.localhost -- y/z/w/w.go -- package w -- v12/go.mod -- module v.localhost -- v12/v.go -- package v -- v11/go.mod -- module v.localhost -- v11/v.go -- package v -- vv/go.mod -- module v.localhost -- vv/v.go -- package v `, "") defer mt.cleanup() mt.assertModuleFoundInDir("example.com/a/b", "b", `main/b$`) mt.assertModuleFoundInDir("example.com/x/v3", "x", `main/v3$`) mt.assertModuleFoundInDir("example.com/y/z/w", "w", `main/y/z/w$`) mt.assertModuleFoundInDir("example.com/vv", "v", `main/v12$`) } // Tests that go.work files are respected. func TestModWorkspace(t *testing.T) { mt := setup(t, nil, ` -- go.work -- go 1.18 use ( ./a ./b ) -- a/go.mod -- module example.com/a go 1.18 -- a/a.go -- package a -- b/go.mod -- module example.com/b go 1.18 -- b/b.go -- package b `, "") defer mt.cleanup() mt.assertModuleFoundInDir("example.com/a", "a", `main/a$`) mt.assertModuleFoundInDir("example.com/b", "b", `main/b$`) mt.assertScanFinds("example.com/a", "a") mt.assertScanFinds("example.com/b", "b") } // Tests replaces in workspaces. Uses the directory layout in the cmd/go // work_replace test. It tests both that replaces in go.work files are // respected and that a wildcard replace in go.work overrides a versioned replace // in go.mod. func TestModWorkspaceReplace(t *testing.T) { mt := setup(t, nil, ` -- go.work -- use m replace example.com/dep => ./dep replace example.com/other => ./other2 -- m/go.mod -- module example.com/m require example.com/dep v1.0.0 require example.com/other v1.0.0 replace example.com/other v1.0.0 => ./other -- m/m.go -- package m import "example.com/dep" import "example.com/other" func F() { dep.G() other.H() } -- dep/go.mod -- module example.com/dep -- dep/dep.go -- package dep func G() { } -- other/go.mod -- module example.com/other -- other/dep.go -- package other func G() { } -- other2/go.mod -- module example.com/other -- other2/dep.go -- package other2 func G() { } `, "") defer mt.cleanup() mt.assertScanFinds("example.com/m", "m") mt.assertScanFinds("example.com/dep", "dep") mt.assertModuleFoundInDir("example.com/other", "other2", "main/other2$") mt.assertScanFinds("example.com/other", "other2") } // Tests a case where conflicting replaces are overridden by a replace // in the go.work file. func TestModWorkspaceReplaceOverride(t *testing.T) { mt := setup(t, nil, `-- go.work -- use m use n replace example.com/dep => ./dep3 -- m/go.mod -- module example.com/m require example.com/dep v1.0.0 replace example.com/dep => ./dep1 -- m/m.go -- package m import "example.com/dep" func F() { dep.G() } -- n/go.mod -- module example.com/n require example.com/dep v1.0.0 replace example.com/dep => ./dep2 -- n/n.go -- package n import "example.com/dep" func F() { dep.G() } -- dep1/go.mod -- module example.com/dep -- dep1/dep.go -- package dep func G() { } -- dep2/go.mod -- module example.com/dep -- dep2/dep.go -- package dep func G() { } -- dep3/go.mod -- module example.com/dep -- dep3/dep.go -- package dep func G() { } `, "") mt.assertScanFinds("example.com/m", "m") mt.assertScanFinds("example.com/n", "n") mt.assertScanFinds("example.com/dep", "dep") mt.assertModuleFoundInDir("example.com/dep", "dep", "main/dep3$") } // Tests that the correct versions of modules are found in // workspaces with module pruning. This is based on the // cmd/go mod_prune_all script test. func TestModWorkspacePrune(t *testing.T) { mt := setup(t, nil, ` -- go.work -- go 1.18 use ( ./a ./p ) replace example.com/b v1.0.0 => ./b replace example.com/q v1.0.0 => ./q1_0_0 replace example.com/q v1.0.5 => ./q1_0_5 replace example.com/q v1.1.0 => ./q1_1_0 replace example.com/r v1.0.0 => ./r replace example.com/w v1.0.0 => ./w replace example.com/x v1.0.0 => ./x replace example.com/y v1.0.0 => ./y replace example.com/z v1.0.0 => ./z1_0_0 replace example.com/z v1.1.0 => ./z1_1_0 -- a/go.mod -- module example.com/a go 1.18 require example.com/b v1.0.0 require example.com/z v1.0.0 -- a/foo.go -- package main import "example.com/b" func main() { b.B() } -- b/go.mod -- module example.com/b go 1.18 require example.com/q v1.1.0 -- b/b.go -- package b func B() { } -- p/go.mod -- module example.com/p go 1.18 require example.com/q v1.0.0 replace example.com/q v1.0.0 => ../q1_0_0 replace example.com/q v1.1.0 => ../q1_1_0 -- p/main.go -- package main import "example.com/q" func main() { q.PrintVersion() } -- q1_0_0/go.mod -- module example.com/q go 1.18 -- q1_0_0/q.go -- package q import "fmt" func PrintVersion() { fmt.Println("version 1.0.0") } -- q1_0_5/go.mod -- module example.com/q go 1.18 require example.com/r v1.0.0 -- q1_0_5/q.go -- package q import _ "example.com/r" -- q1_1_0/go.mod -- module example.com/q require example.com/w v1.0.0 require example.com/z v1.1.0 go 1.18 -- q1_1_0/q.go -- package q import _ "example.com/w" import _ "example.com/z" import "fmt" func PrintVersion() { fmt.Println("version 1.1.0") } -- r/go.mod -- module example.com/r go 1.18 require example.com/r v1.0.0 -- r/r.go -- package r -- w/go.mod -- module example.com/w go 1.18 require example.com/x v1.0.0 -- w/w.go -- package w -- w/w_test.go -- package w import _ "example.com/x" -- x/go.mod -- module example.com/x go 1.18 -- x/x.go -- package x -- x/x_test.go -- package x import _ "example.com/y" -- y/go.mod -- module example.com/y go 1.18 -- y/y.go -- package y -- z1_0_0/go.mod -- module example.com/z go 1.18 require example.com/q v1.0.5 -- z1_0_0/z.go -- package z import _ "example.com/q" -- z1_1_0/go.mod -- module example.com/z go 1.18 -- z1_1_0/z.go -- package z `, "") mt.assertScanFinds("example.com/w", "w") mt.assertScanFinds("example.com/q", "q") mt.assertScanFinds("example.com/x", "x") mt.assertScanFinds("example.com/z", "z") mt.assertModuleFoundInDir("example.com/w", "w", "main/w$") mt.assertModuleFoundInDir("example.com/q", "q", "main/q1_1_0$") mt.assertModuleFoundInDir("example.com/x", "x", "main/x$") mt.assertModuleFoundInDir("example.com/z", "z", "main/z1_1_0$") } // Tests that we handle GO111MODULE=on with no go.mod file. See #30855. func TestNoMainModule(t *testing.T) { mt := setup(t, map[string]string{"GO111MODULE": "on"}, ` -- x.go -- package x `, "") defer mt.cleanup() if _, err := mt.env.invokeGo(context.Background(), "mod", "download", "rsc.io/quote@v1.5.1"); err != nil { t.Fatal(err) } mt.assertScanFinds("rsc.io/quote", "quote") } // assertFound asserts that the package at importPath is found to have pkgName, // and that scanning for pkgName finds it at importPath. func (t *modTest) assertFound(importPath, pkgName string) (string, *pkg) { t.Helper() names, err := t.env.resolver.loadPackageNames([]string{importPath}, t.env.WorkingDir) if err != nil { t.Errorf("loading package name for %v: %v", importPath, err) } if names[importPath] != pkgName { t.Errorf("package name for %v = %v, want %v", importPath, names[importPath], pkgName) } pkg := t.assertScanFinds(importPath, pkgName) _, foundDir := t.env.resolver.(*ModuleResolver).findPackage(importPath) return foundDir, pkg } func (t *modTest) assertScanFinds(importPath, pkgName string) *pkg { t.Helper() scan, err := scanToSlice(t.env.resolver, nil) if err != nil { t.Errorf("scan failed: %v", err) } for _, pkg := range scan { if pkg.importPathShort == importPath { return pkg } } t.Errorf("scanning for %v did not find %v", pkgName, importPath) return nil } func scanToSlice(resolver Resolver, exclude []gopathwalk.RootType) ([]*pkg, error) { var mu sync.Mutex var result []*pkg filter := &scanCallback{ rootFound: func(root gopathwalk.Root) bool { for _, rt := range exclude { if root.Type == rt { return false } } return true }, dirFound: func(pkg *pkg) bool { return true }, packageNameLoaded: func(pkg *pkg) bool { mu.Lock() defer mu.Unlock() result = append(result, pkg) return false }, } err := resolver.scan(context.Background(), filter) return result, err } // assertModuleFoundInDir is the same as assertFound, but also checks that the // package was found in an active module whose Dir matches dirRE. func (t *modTest) assertModuleFoundInDir(importPath, pkgName, dirRE string) { t.Helper() dir, pkg := t.assertFound(importPath, pkgName) re, err := regexp.Compile(dirRE) if err != nil { t.Fatal(err) } if dir == "" { t.Errorf("import path %v not found in active modules", importPath) } else { if !re.MatchString(filepath.ToSlash(dir)) { t.Errorf("finding dir for %s: dir = %q did not match regex %q", importPath, dir, dirRE) } } if pkg != nil { if !re.MatchString(filepath.ToSlash(pkg.dir)) { t.Errorf("scanning for %s: dir = %q did not match regex %q", pkgName, pkg.dir, dirRE) } } } var proxyOnce sync.Once var proxyDir string type modTest struct { *testing.T env *ProcessEnv gopath string cleanup func() } // setup builds a test environment from a txtar and supporting modules // in testdata/mod, along the lines of TestScript in cmd/go. // // extraEnv is applied on top of the default test env. func setup(t *testing.T, extraEnv map[string]string, main, wd string) *modTest { t.Helper() testenv.NeedsTool(t, "go") proxyOnce.Do(func() { var err error proxyDir, err = os.MkdirTemp("", "proxy-") if err != nil { t.Fatal(err) } if err := writeProxy(proxyDir, "testdata/mod"); err != nil { t.Fatal(err) } }) dir, err := os.MkdirTemp("", t.Name()) if err != nil { t.Fatal(err) } mainDir := filepath.Join(dir, "main") if err := writeModule(mainDir, main); err != nil { t.Fatal(err) } env := &ProcessEnv{ Env: map[string]string{ "GOPATH": filepath.Join(dir, "gopath"), "GOMODCACHE": "", "GO111MODULE": "auto", "GOSUMDB": "off", "GOPROXY": proxydir.ToURL(proxyDir), }, WorkingDir: filepath.Join(mainDir, wd), GocmdRunner: &gocommand.Runner{}, } for k, v := range extraEnv { env.Env[k] = v } if *testDebug { env.Logf = log.Printf } // go mod download gets mad if we don't have a go.mod, so make sure we do. _, err = os.Stat(filepath.Join(mainDir, "go.mod")) if err != nil && !os.IsNotExist(err) { t.Fatalf("checking if go.mod exists: %v", err) } if err == nil { if _, err := env.invokeGo(context.Background(), "mod", "download", "all"); err != nil { t.Fatal(err) } } // Ensure the resolver is set for tests that (unsafely) access env.resolver // directly. // // TODO(rfindley): fix this after addressing the TODO in the ProcessEnv // docstring. if _, err := env.GetResolver(); err != nil { t.Fatal(err) } return &modTest{ T: t, gopath: env.Env["GOPATH"], env: env, cleanup: func() { removeDir(dir) }, } } // writeModule writes the module in the ar, a txtar, to dir. func writeModule(dir, ar string) error { a := txtar.Parse([]byte(ar)) for _, f := range a.Files { fpath := filepath.Join(dir, f.Name) if err := os.MkdirAll(filepath.Dir(fpath), 0755); err != nil { return err } if err := os.WriteFile(fpath, f.Data, 0644); err != nil { return err } } return nil } // writeProxy writes all the txtar-formatted modules in arDir to a proxy // directory in dir. func writeProxy(dir, arDir string) error { files, err := os.ReadDir(arDir) if err != nil { return err } for _, fi := range files { if err := writeProxyModule(dir, filepath.Join(arDir, fi.Name())); err != nil { return err } } return nil } // writeProxyModule writes a txtar-formatted module at arPath to the module // proxy in base. func writeProxyModule(base, arPath string) error { arName := filepath.Base(arPath) i := strings.LastIndex(arName, "_v") ver := strings.TrimSuffix(arName[i+1:], ".txt") modDir := strings.ReplaceAll(arName[:i], "_", "/") modPath, err := module.UnescapePath(modDir) if err != nil { return err } dir := filepath.Join(base, modDir, "@v") a, err := txtar.ParseFile(arPath) if err != nil { return err } if err := os.MkdirAll(dir, 0755); err != nil { return err } f, err := os.OpenFile(filepath.Join(dir, ver+".zip"), os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return err } z := zip.NewWriter(f) for _, f := range a.Files { if f.Name[0] == '.' { if err := os.WriteFile(filepath.Join(dir, ver+f.Name), f.Data, 0644); err != nil { return err } } else { zf, err := z.Create(modPath + "@" + ver + "/" + f.Name) if err != nil { return err } if _, err := zf.Write(f.Data); err != nil { return err } } } if err := z.Close(); err != nil { return err } if err := f.Close(); err != nil { return err } list, err := os.OpenFile(filepath.Join(dir, "list"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { return err } if _, err := fmt.Fprintf(list, "%s\n", ver); err != nil { return err } if err := list.Close(); err != nil { return err } return nil } func removeDir(dir string) { _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return nil } if info.IsDir() { _ = os.Chmod(path, 0777) } return nil }) _ = os.RemoveAll(dir) // ignore errors } // Tests that findModFile can find the mod files from a path in the module cache. func TestFindModFileModCache(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module x require rsc.io/quote v1.5.2 -- x.go -- package x import _ "rsc.io/quote" `, "") defer mt.cleanup() want := filepath.Join(mt.gopath, "pkg/mod", "rsc.io/quote@v1.5.2") found := mt.assertScanFinds("rsc.io/quote", "quote") modDir, _ := mt.env.resolver.(*ModuleResolver).modInfo(found.dir) if modDir != want { t.Errorf("expected: %s, got: %s", want, modDir) } } // Tests that crud in the module cache is ignored. func TestInvalidModCache(t *testing.T) { testenv.NeedsTool(t, "go") dir, err := os.MkdirTemp("", t.Name()) if err != nil { t.Fatal(err) } defer removeDir(dir) // This doesn't have module@version like it should. if err := os.MkdirAll(filepath.Join(dir, "gopath/pkg/mod/sabotage"), 0777); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(dir, "gopath/pkg/mod/sabotage/x.go"), []byte("package foo\n"), 0777); err != nil { t.Fatal(err) } env := &ProcessEnv{ Env: map[string]string{ "GOPATH": filepath.Join(dir, "gopath"), "GO111MODULE": "on", "GOSUMDB": "off", }, GocmdRunner: &gocommand.Runner{}, WorkingDir: dir, } resolver, err := env.GetResolver() if err != nil { t.Fatal(err) } scanToSlice(resolver, nil) } func TestGetCandidatesRanking(t *testing.T) { mt := setup(t, nil, ` -- go.mod -- module example.com require rsc.io/quote v1.5.1 require rsc.io/quote/v3 v3.0.0 -- rpackage/x.go -- package rpackage import ( _ "rsc.io/quote" _ "rsc.io/quote/v3" ) `, "") defer mt.cleanup() if _, err := mt.env.invokeGo(context.Background(), "mod", "download", "rsc.io/quote/v2@v2.0.1"); err != nil { t.Fatal(err) } type res struct { relevance float64 name, path string } want := []res{ // Stdlib {7, "bytes", "bytes"}, {7, "http", "net/http"}, // Main module {6, "rpackage", "example.com/rpackage"}, // Direct module deps with v2+ major version {5.003, "quote", "rsc.io/quote/v3"}, // Direct module deps {5, "quote", "rsc.io/quote"}, // Indirect deps {4, "language", "golang.org/x/text/language"}, // Out of scope modules {3, "quote", "rsc.io/quote/v2"}, } var mu sync.Mutex var got []res add := func(c ImportFix) { mu.Lock() defer mu.Unlock() for _, w := range want { if c.StmtInfo.ImportPath == w.path { got = append(got, res{c.Relevance, c.IdentName, c.StmtInfo.ImportPath}) } } } if err := GetAllCandidates(context.Background(), add, "", "foo.go", "foo", mt.env); err != nil { t.Fatalf("getAllCandidates() = %v", err) } sort.Slice(got, func(i, j int) bool { ri, rj := got[i], got[j] if ri.relevance != rj.relevance { return ri.relevance > rj.relevance // Highest first. } return ri.name < rj.name }) if !reflect.DeepEqual(want, got) { t.Errorf("wanted candidates in order %v, got %v", want, got) } } func BenchmarkModuleResolver_RescanModCache(b *testing.B) { env := &ProcessEnv{ GocmdRunner: &gocommand.Runner{}, // Uncomment for verbose logging (too verbose to enable by default). // Logf: b.Logf, } exclude := []gopathwalk.RootType{gopathwalk.RootGOROOT} resolver, err := env.GetResolver() if err != nil { b.Fatal(err) } start := time.Now() scanToSlice(resolver, exclude) b.Logf("warming the mod cache took %v", time.Since(start)) b.ResetTimer() for i := 0; i < b.N; i++ { scanToSlice(resolver, exclude) resolver = resolver.ClearForNewScan() } } func BenchmarkModuleResolver_InitialScan(b *testing.B) { for i := 0; i < b.N; i++ { env := &ProcessEnv{ GocmdRunner: &gocommand.Runner{}, } exclude := []gopathwalk.RootType{gopathwalk.RootGOROOT} resolver, err := env.GetResolver() if err != nil { b.Fatal(err) } scanToSlice(resolver, exclude) } }
tools/internal/imports/mod_test.go/0
{ "file_path": "tools/internal/imports/mod_test.go", "repo_id": "tools", "token_count": 12013 }
767
// 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 jsonrpc2 import "golang.org/x/tools/internal/event/keys" // These keys are used for creating labels to instrument jsonrpc2 events. var ( Method = keys.NewString("method", "") RPCID = keys.NewString("id", "") RPCDirection = keys.NewString("direction", "") Started = keys.NewInt64("started", "Count of started RPCs.") SentBytes = keys.NewInt64("sent_bytes", "Bytes sent.") //, unit.Bytes) ReceivedBytes = keys.NewInt64("received_bytes", "Bytes received.") //, unit.Bytes) StatusCode = keys.NewString("status.code", "") Latency = keys.NewFloat64("latency_ms", "Elapsed time in milliseconds") //, unit.Milliseconds) ) const ( Inbound = "in" Outbound = "out" )
tools/internal/jsonrpc2/labels.go/0
{ "file_path": "tools/internal/jsonrpc2/labels.go", "repo_id": "tools", "token_count": 318 }
768
// 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 // This file defines the analysis of the callee function. import ( "bytes" "encoding/gob" "fmt" "go/ast" "go/parser" "go/token" "go/types" "strings" "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/types/typeutil" "golang.org/x/tools/internal/typeparams" ) // A Callee holds information about an inlinable function. Gob-serializable. type Callee struct { impl gobCallee } func (callee *Callee) String() string { return callee.impl.Name } type gobCallee struct { Content []byte // file content, compacted to a single func decl // results of type analysis (does not reach go/types data structures) PkgPath string // package path of declaring package Name string // user-friendly name for error messages Unexported []string // names of free objects that are unexported FreeRefs []freeRef // locations of references to free objects FreeObjs []object // descriptions of free objects ValidForCallStmt bool // function body is "return expr" where expr is f() or <-ch NumResults int // number of results (according to type, not ast.FieldList) Params []*paramInfo // information about parameters (incl. receiver) Results []*paramInfo // information about result variables Effects []int // order in which parameters are evaluated (see calleefx) HasDefer bool // uses defer HasBareReturn bool // uses bare return in non-void function Returns [][]returnOperandFlags // metadata about result expressions for each return Labels []string // names of all control labels Falcon falconResult // falcon constraint system } // returnOperandFlags records metadata about a single result expression in a return // statement. type returnOperandFlags int const ( nonTrivialResult returnOperandFlags = 1 << iota // return operand has non-trivial conversion to result type untypedNilResult // return operand is nil literal ) // A freeRef records a reference to a free object. Gob-serializable. // (This means free relative to the FuncDecl as a whole, i.e. excluding parameters.) type freeRef struct { Offset int // byte offset of the reference relative to the FuncDecl Object int // index into Callee.freeObjs } // An object abstracts a free types.Object referenced by the callee. Gob-serializable. type object struct { Name string // Object.Name() Kind string // one of {var,func,const,type,pkgname,nil,builtin} PkgPath string // path of object's package (or imported package if kind="pkgname") PkgName string // name of object's package (or imported package if kind="pkgname") // TODO(rfindley): should we also track LocalPkgName here? Do we want to // preserve the local package name? ValidPos bool // Object.Pos().IsValid() Shadow map[string]bool // names shadowed at one of the object's refs } // AnalyzeCallee analyzes a function that is a candidate for inlining // and returns a Callee that describes it. The Callee object, which is // serializable, can be passed to one or more subsequent calls to // Inline, each with a different Caller. // // This design allows separate analysis of callers and callees in the // golang.org/x/tools/go/analysis framework: the inlining information // about a callee can be recorded as a "fact". // // The content should be the actual input to the compiler, not the // apparent source file according to any //line directives that // may be present within it. func AnalyzeCallee(logf func(string, ...any), fset *token.FileSet, pkg *types.Package, info *types.Info, decl *ast.FuncDecl, content []byte) (*Callee, error) { checkInfoFields(info) // The client is expected to have determined that the callee // is a function with a declaration (not a built-in or var). fn := info.Defs[decl.Name].(*types.Func) sig := fn.Type().(*types.Signature) logf("analyzeCallee %v @ %v", fn, fset.PositionFor(decl.Pos(), false)) // Create user-friendly name ("pkg.Func" or "(pkg.T).Method") var name string if sig.Recv() == nil { name = fmt.Sprintf("%s.%s", fn.Pkg().Name(), fn.Name()) } else { name = fmt.Sprintf("(%s).%s", types.TypeString(sig.Recv().Type(), (*types.Package).Name), fn.Name()) } if decl.Body == nil { return nil, fmt.Errorf("cannot inline function %s as it has no body", name) } // TODO(adonovan): support inlining of instantiated generic // functions by replacing each occurrence of a type parameter // T by its instantiating type argument (e.g. int). We'll need // to wrap the instantiating type in parens when it's not an // ident or qualified ident to prevent "if x == struct{}" // parsing ambiguity, or "T(x)" where T = "*int" or "func()" // from misparsing. if funcHasTypeParams(decl) { return nil, fmt.Errorf("cannot inline generic function %s: type parameters are not yet supported", name) } // Record the location of all free references in the FuncDecl. // (Parameters are not free by this definition.) var ( freeObjIndex = make(map[types.Object]int) freeObjs []object freeRefs []freeRef // free refs that may need renaming unexported []string // free refs to unexported objects, for later error checks ) var f func(n ast.Node) bool visit := func(n ast.Node) { ast.Inspect(n, f) } var stack []ast.Node stack = append(stack, decl.Type) // for scope of function itself f = func(n ast.Node) bool { if n != nil { stack = append(stack, n) // push } else { stack = stack[:len(stack)-1] // pop } switch n := n.(type) { case *ast.SelectorExpr: // Check selections of free fields/methods. if sel, ok := info.Selections[n]; ok && !within(sel.Obj().Pos(), decl) && !n.Sel.IsExported() { sym := fmt.Sprintf("(%s).%s", info.TypeOf(n.X), n.Sel.Name) unexported = append(unexported, sym) } // Don't recur into SelectorExpr.Sel. visit(n.X) return false case *ast.CompositeLit: // Check for struct literals that refer to unexported fields, // whether keyed or unkeyed. (Logic assumes well-typedness.) litType := typeparams.Deref(info.TypeOf(n)) if s, ok := typeparams.CoreType(litType).(*types.Struct); ok { if n.Type != nil { visit(n.Type) } for i, elt := range n.Elts { var field *types.Var var value ast.Expr if kv, ok := elt.(*ast.KeyValueExpr); ok { field = info.Uses[kv.Key.(*ast.Ident)].(*types.Var) value = kv.Value } else { field = s.Field(i) value = elt } if !within(field.Pos(), decl) && !field.Exported() { sym := fmt.Sprintf("(%s).%s", litType, field.Name()) unexported = append(unexported, sym) } // Don't recur into KeyValueExpr.Key. visit(value) } return false } case *ast.Ident: if obj, ok := info.Uses[n]; ok { // Methods and fields are handled by SelectorExpr and CompositeLit. if isField(obj) || isMethod(obj) { panic(obj) } // Inv: id is a lexical reference. // A reference to an unexported package-level declaration // cannot be inlined into another package. if !n.IsExported() && obj.Pkg() != nil && obj.Parent() == obj.Pkg().Scope() { unexported = append(unexported, n.Name) } // Record free reference (incl. self-reference). if obj == fn || !within(obj.Pos(), decl) { objidx, ok := freeObjIndex[obj] if !ok { objidx = len(freeObjIndex) var pkgpath, pkgname string if pn, ok := obj.(*types.PkgName); ok { pkgpath = pn.Imported().Path() pkgname = pn.Imported().Name() } else if obj.Pkg() != nil { pkgpath = obj.Pkg().Path() pkgname = obj.Pkg().Name() } freeObjs = append(freeObjs, object{ Name: obj.Name(), Kind: objectKind(obj), PkgName: pkgname, PkgPath: pkgpath, ValidPos: obj.Pos().IsValid(), }) freeObjIndex[obj] = objidx } freeObjs[objidx].Shadow = addShadows(freeObjs[objidx].Shadow, info, obj.Name(), stack) freeRefs = append(freeRefs, freeRef{ Offset: int(n.Pos() - decl.Pos()), Object: objidx, }) } } } return true } visit(decl) // Analyze callee body for "return expr" form, // where expr is f() or <-ch. These forms are // safe to inline as a standalone statement. validForCallStmt := false if len(decl.Body.List) != 1 { // not just a return statement } else if ret, ok := decl.Body.List[0].(*ast.ReturnStmt); ok && len(ret.Results) == 1 { validForCallStmt = func() bool { switch expr := astutil.Unparen(ret.Results[0]).(type) { case *ast.CallExpr: // f(x) callee := typeutil.Callee(info, expr) if callee == nil { return false // conversion T(x) } // The only non-void built-in functions that may be // called as a statement are copy and recover // (though arguably a call to recover should never // be inlined as that changes its behavior). if builtin, ok := callee.(*types.Builtin); ok { return builtin.Name() == "copy" || builtin.Name() == "recover" } return true // ordinary call f() case *ast.UnaryExpr: // <-x return expr.Op == token.ARROW // channel receive <-ch } // No other expressions are valid statements. return false }() } // Record information about control flow in the callee // (but not any nested functions). var ( hasDefer = false hasBareReturn = false returnInfo [][]returnOperandFlags labels []string ) ast.Inspect(decl.Body, func(n ast.Node) bool { switch n := n.(type) { case *ast.FuncLit: return false // prune traversal case *ast.DeferStmt: hasDefer = true case *ast.LabeledStmt: labels = append(labels, n.Label.Name) case *ast.ReturnStmt: // Are implicit assignment conversions // to result variables all trivial? var resultInfo []returnOperandFlags if len(n.Results) > 0 { argInfo := func(i int) (ast.Expr, types.Type) { expr := n.Results[i] return expr, info.TypeOf(expr) } if len(n.Results) == 1 && sig.Results().Len() > 1 { // Spread return: return f() where f.Results > 1. tuple := info.TypeOf(n.Results[0]).(*types.Tuple) argInfo = func(i int) (ast.Expr, types.Type) { return nil, tuple.At(i).Type() } } for i := 0; i < sig.Results().Len(); i++ { expr, typ := argInfo(i) var flags returnOperandFlags if typ == types.Typ[types.UntypedNil] { // untyped nil is preserved by go/types flags |= untypedNilResult } if !trivialConversion(info.Types[expr].Value, typ, sig.Results().At(i).Type()) { flags |= nonTrivialResult } resultInfo = append(resultInfo, flags) } } else if sig.Results().Len() > 0 { hasBareReturn = true } returnInfo = append(returnInfo, resultInfo) } return true }) // Reject attempts to inline cgo-generated functions. for _, obj := range freeObjs { // There are others (iconst fconst sconst fpvar macro) // but this is probably sufficient. if strings.HasPrefix(obj.Name, "_Cfunc_") || strings.HasPrefix(obj.Name, "_Ctype_") || strings.HasPrefix(obj.Name, "_Cvar_") { return nil, fmt.Errorf("cannot inline cgo-generated functions") } } // Compact content to just the FuncDecl. // // As a space optimization, we don't retain the complete // callee file content; all we need is "package _; func f() { ... }". // This reduces the size of analysis facts. // // Offsets in the callee information are "relocatable" // since they are all relative to the FuncDecl. content = append([]byte("package _\n"), content[offsetOf(fset, decl.Pos()):offsetOf(fset, decl.End())]...) // Sanity check: re-parse the compacted content. if _, _, err := parseCompact(content); err != nil { return nil, err } params, results, effects, falcon := analyzeParams(logf, fset, info, decl) return &Callee{gobCallee{ Content: content, PkgPath: pkg.Path(), Name: name, Unexported: unexported, FreeObjs: freeObjs, FreeRefs: freeRefs, ValidForCallStmt: validForCallStmt, NumResults: sig.Results().Len(), Params: params, Results: results, Effects: effects, HasDefer: hasDefer, HasBareReturn: hasBareReturn, Returns: returnInfo, Labels: labels, Falcon: falcon, }}, nil } // parseCompact parses a Go source file of the form "package _\n func f() { ... }" // and returns the sole function declaration. func parseCompact(content []byte) (*token.FileSet, *ast.FuncDecl, error) { fset := token.NewFileSet() const mode = parser.ParseComments | parser.SkipObjectResolution | parser.AllErrors f, err := parser.ParseFile(fset, "callee.go", content, mode) if err != nil { return nil, nil, fmt.Errorf("internal error: cannot compact file: %v", err) } return fset, f.Decls[0].(*ast.FuncDecl), nil } // A paramInfo records information about a callee receiver, parameter, or result variable. type paramInfo struct { Name string // parameter name (may be blank, or even "") Index int // index within signature IsResult bool // false for receiver or parameter, true for result variable Assigned bool // parameter appears on left side of an assignment statement Escapes bool // parameter has its address taken Refs []int // FuncDecl-relative byte offset of parameter ref within body Shadow map[string]bool // names shadowed at one of the above refs FalconType string // name of this parameter's type (if basic) in the falcon system } // analyzeParams computes information about parameters of function fn, // including a simple "address taken" escape analysis. // // It returns two new arrays, one of the receiver and parameters, and // the other of the result variables of function fn. // // The input must be well-typed. func analyzeParams(logf func(string, ...any), fset *token.FileSet, info *types.Info, decl *ast.FuncDecl) (params, results []*paramInfo, effects []int, _ falconResult) { fnobj, ok := info.Defs[decl.Name] if !ok { panic(fmt.Sprintf("%s: no func object for %q", fset.PositionFor(decl.Name.Pos(), false), decl.Name)) // ill-typed? } paramInfos := make(map[*types.Var]*paramInfo) { sig := fnobj.Type().(*types.Signature) newParamInfo := func(param *types.Var, isResult bool) *paramInfo { info := &paramInfo{ Name: param.Name(), IsResult: isResult, Index: len(paramInfos), } paramInfos[param] = info return info } if sig.Recv() != nil { params = append(params, newParamInfo(sig.Recv(), false)) } for i := 0; i < sig.Params().Len(); i++ { params = append(params, newParamInfo(sig.Params().At(i), false)) } for i := 0; i < sig.Results().Len(); i++ { results = append(results, newParamInfo(sig.Results().At(i), true)) } } // Search function body for operations &x, x.f(), and x = y // where x is a parameter, and record it. escape(info, decl, func(v *types.Var, escapes bool) { if info := paramInfos[v]; info != nil { if escapes { info.Escapes = true } else { info.Assigned = true } } }) // Record locations of all references to parameters. // And record the set of intervening definitions for each parameter. // // TODO(adonovan): combine this traversal with the one that computes // FreeRefs. The tricky part is that calleefx needs this one first. var stack []ast.Node stack = append(stack, decl.Type) // for scope of function itself ast.Inspect(decl.Body, func(n ast.Node) bool { if n != nil { stack = append(stack, n) // push } else { stack = stack[:len(stack)-1] // pop } if id, ok := n.(*ast.Ident); ok { if v, ok := info.Uses[id].(*types.Var); ok { if pinfo, ok := paramInfos[v]; ok { // Record location of ref to parameter/result // and any intervening (shadowing) names. offset := int(n.Pos() - decl.Pos()) pinfo.Refs = append(pinfo.Refs, offset) pinfo.Shadow = addShadows(pinfo.Shadow, info, pinfo.Name, stack) } } } return true }) // Compute subset and order of parameters that are strictly evaluated. // (Depends on Refs computed above.) effects = calleefx(info, decl.Body, paramInfos) logf("effects list = %v", effects) falcon := falcon(logf, fset, paramInfos, info, decl) return params, results, effects, falcon } // -- callee helpers -- // addShadows returns the shadows set augmented by the set of names // locally shadowed at the location of the reference in the callee // (identified by the stack). The name of the reference itself is // excluded. // // These shadowed names may not be used in a replacement expression // for the reference. func addShadows(shadows map[string]bool, info *types.Info, exclude string, stack []ast.Node) map[string]bool { for _, n := range stack { if scope := scopeFor(info, n); scope != nil { for _, name := range scope.Names() { if name != exclude { if shadows == nil { shadows = make(map[string]bool) } shadows[name] = true } } } } return shadows } func isField(obj types.Object) bool { if v, ok := obj.(*types.Var); ok && v.IsField() { return true } return false } func isMethod(obj types.Object) bool { if f, ok := obj.(*types.Func); ok && f.Type().(*types.Signature).Recv() != nil { return true } return false } // -- serialization -- var ( _ gob.GobEncoder = (*Callee)(nil) _ gob.GobDecoder = (*Callee)(nil) ) func (callee *Callee) GobEncode() ([]byte, error) { var out bytes.Buffer if err := gob.NewEncoder(&out).Encode(callee.impl); err != nil { return nil, err } return out.Bytes(), nil } func (callee *Callee) GobDecode(data []byte) error { return gob.NewDecoder(bytes.NewReader(data)).Decode(&callee.impl) }
tools/internal/refactor/inline/callee.go/0
{ "file_path": "tools/internal/refactor/inline/callee.go", "repo_id": "tools", "token_count": 7065 }
769
A self-reference counts as a free reference, so that it gets properly package-qualified as needed. (Regression test for a bug.) -- go.mod -- module testdata go 1.12 -- a/a.go -- package a import "testdata/b" func _() { b.F(1) //@ inline(re"F", output) } -- b/b.go -- package b func F(x int) { F(x + 2) } -- output -- package a import "testdata/b" func _() { b.F(1 + 2) //@ inline(re"F", output) }
tools/internal/refactor/inline/testdata/crosspkg-selfref.txtar/0
{ "file_path": "tools/internal/refactor/inline/testdata/crosspkg-selfref.txtar", "repo_id": "tools", "token_count": 171 }
770
Test of inlining a method call. The call to (*T).g0 implicitly takes the address &x, and the call to T.h implictly dereferences the argument *ptr. The f1/g1 methods have parameters, exercising the splicing of the receiver into the parameter list. Notice that the unnamed parameters become named. -- go.mod -- module testdata go 1.12 -- a/f0.go -- package a type T int func (recv T) f0() { println(recv) } func _(x T) { x.f0() //@ inline(re"f0", f0) } -- f0 -- package a type T int func (recv T) f0() { println(recv) } func _(x T) { println(x) //@ inline(re"f0", f0) } -- a/g0.go -- package a func (recv *T) g0() { println(recv) } func _(x T) { x.g0() //@ inline(re"g0", g0) } -- g0 -- package a func (recv *T) g0() { println(recv) } func _(x T) { println(&x) //@ inline(re"g0", g0) } -- a/f1.go -- package a func (recv T) f1(int, int) { println(recv) } func _(x T) { x.f1(1, 2) //@ inline(re"f1", f1) } -- f1 -- package a func (recv T) f1(int, int) { println(recv) } func _(x T) { println(x) //@ inline(re"f1", f1) } -- a/g1.go -- package a func (recv *T) g1(int, int) { println(recv) } func _(x T) { x.g1(1, 2) //@ inline(re"g1", g1) } -- g1 -- package a func (recv *T) g1(int, int) { println(recv) } func _(x T) { println(&x) //@ inline(re"g1", g1) } -- a/h.go -- package a func (T) h() int { return 1 } func _() { var ptr *T ptr.h() //@ inline(re"h", h) } -- h -- package a func (T) h() int { return 1 } func _() { var ptr *T var _ T = *ptr _ = 1 //@ inline(re"h", h) } -- a/i.go -- package a func (T) i() int { return 1 } func _() { (*T).i(nil) //@ inline(re"i", i) } -- i -- package a func (T) i() int { return 1 } func _() { _ = 1 //@ inline(re"i", i) }
tools/internal/refactor/inline/testdata/method.txtar/0
{ "file_path": "tools/internal/refactor/inline/testdata/method.txtar", "repo_id": "tools", "token_count": 810 }
771
// 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 robustio_test import ( "os" "path/filepath" "runtime" "testing" "time" "golang.org/x/tools/internal/robustio" ) func checkOSLink(t *testing.T, err error) { if err == nil { return } t.Helper() switch runtime.GOOS { case "aix", "darwin", "dragonfly", "freebsd", "illumos", "linux", "netbsd", "openbsd", "solaris": // Non-mobile OS known to always support os.Symlink and os.Link. t.Fatal(err) default: t.Skipf("skipping due to error on %v: %v", runtime.GOOS, err) } } func TestFileInfo(t *testing.T) { // A nonexistent file has no ID. nonexistent := filepath.Join(t.TempDir(), "nonexistent") if _, _, err := robustio.GetFileID(nonexistent); err == nil { t.Fatalf("GetFileID(nonexistent) succeeded unexpectedly") } // A regular file has an ID. real := filepath.Join(t.TempDir(), "real") if err := os.WriteFile(real, nil, 0644); err != nil { t.Fatalf("can't create regular file: %v", err) } realID, realMtime, err := robustio.GetFileID(real) if err != nil { t.Fatalf("can't get ID of regular file: %v", err) } // Sleep so that we get a new mtime for subsequent writes. time.Sleep(2 * time.Second) // A second regular file has a different ID. real2 := filepath.Join(t.TempDir(), "real2") if err := os.WriteFile(real2, nil, 0644); err != nil { t.Fatalf("can't create second regular file: %v", err) } real2ID, real2Mtime, err := robustio.GetFileID(real2) if err != nil { t.Fatalf("can't get ID of second regular file: %v", err) } if realID == real2ID { t.Errorf("realID %+v == real2ID %+v", realID, real2ID) } if realMtime.Equal(real2Mtime) { t.Errorf("realMtime %v == real2Mtime %v", realMtime, real2Mtime) } // A symbolic link has the same ID as its target. t.Run("symlink", func(t *testing.T) { symlink := filepath.Join(t.TempDir(), "symlink") checkOSLink(t, os.Symlink(real, symlink)) symlinkID, symlinkMtime, err := robustio.GetFileID(symlink) if err != nil { t.Fatalf("can't get ID of symbolic link: %v", err) } if realID != symlinkID { t.Errorf("realID %+v != symlinkID %+v", realID, symlinkID) } if !realMtime.Equal(symlinkMtime) { t.Errorf("realMtime %v != symlinkMtime %v", realMtime, symlinkMtime) } }) // Two hard-linked files have the same ID. t.Run("hardlink", func(t *testing.T) { hardlink := filepath.Join(t.TempDir(), "hardlink") checkOSLink(t, os.Link(real, hardlink)) hardlinkID, hardlinkMtime, err := robustio.GetFileID(hardlink) if err != nil { t.Fatalf("can't get ID of hard link: %v", err) } if realID != hardlinkID { t.Errorf("realID %+v != hardlinkID %+v", realID, hardlinkID) } if !realMtime.Equal(hardlinkMtime) { t.Errorf("realMtime %v != hardlinkMtime %v", realMtime, hardlinkMtime) } }) }
tools/internal/robustio/robustio_test.go/0
{ "file_path": "tools/internal/robustio/robustio_test.go", "repo_id": "tools", "token_count": 1189 }
772
// File is versions/go.mod after expansion with TestDir() module golang.org/fake/versions go 1.21
tools/internal/testfiles/testdata/versions/go.mod.test/0
{ "file_path": "tools/internal/testfiles/testdata/versions/go.mod.test", "repo_id": "tools", "token_count": 32 }
773
// 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 ( "go/ast" "go/parser" "go/token" "go/types" "testing" ) func TestFree(t *testing.T) { const source = ` package P type A int func (A) f() func (*A) g() type fer interface { f() } func Apply[T fer](x T) T { x.f() return x } type V[T any] []T func (v *V[T]) Push(x T) { *v = append(*v, x) } ` fset := token.NewFileSet() f, err := parser.ParseFile(fset, "hello.go", source, 0) if err != nil { t.Fatal(err) } var conf types.Config pkg, err := conf.Check("P", fset, []*ast.File{f}, nil) if err != nil { t.Fatal(err) } for _, test := range []struct { expr string // type expression want bool // expected value }{ {"A", false}, {"*A", false}, {"error", false}, {"*error", false}, {"struct{A}", false}, {"*struct{A}", false}, {"fer", false}, {"Apply", true}, {"Apply[A]", false}, {"V", true}, {"V[A]", false}, {"*V[A]", false}, {"(*V[A]).Push", false}, } { tv, err := types.Eval(fset, pkg, 0, test.expr) if err != nil { t.Errorf("Eval(%s) failed: %v", test.expr, err) } if got := new(Free).Has(tv.Type); got != test.want { t.Logf("Eval(%s) returned the type %s", test.expr, tv.Type) t.Errorf("isParameterized(%s) = %v, want %v", test.expr, got, test.want) } } }
tools/internal/typeparams/free_test.go/0
{ "file_path": "tools/internal/typeparams/free_test.go", "repo_id": "tools", "token_count": 622 }
774
// Copyright 2011 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 implements parsing and rendering of present files, which can be slide presentations as in golang.org/x/tools/cmd/present or articles as in golang.org/x/blog (the Go blog). # File Format Present files begin with a header giving the title of the document and other metadata, which looks like: # Title of document Subtitle of document 15:04 2 Jan 2006 Tags: foo, bar, baz Summary: This is a great document you want to read. OldURL: former-path-for-this-doc The "# " prefix before the title indicates that this is a Markdown-enabled present file: it uses Markdown for text markup in the body of the file. If the "# " prefix is missing, the file uses legacy present markup, described below. The date line may be written without a time: 2 Jan 2006 In this case, the time will be interpreted as 10am UTC on that date. The tags line is a comma-separated list of tags that may be used to categorize the document. The summary line gives a short summary used in blog feeds. The old URL line, which may be repeated, gives an older (perhaps relative) URL for this document. A server might use these to generate appropriate redirects. Only the title is required; the subtitle, date, tags, summary, and old URL lines are optional. In Markdown-enabled present, the summary defaults to being empty. In legacy present, the summary defaults to the first paragraph of text. After the header come zero or more author blocks, like this: Author Name Job title, Company joe@example.com https://url/ @twitter_name The first line of the author block is conventionally the author name. Otherwise, the author section may contain a mixture of text, twitter names, and links. For slide presentations, only the plain text lines will be displayed on the first slide. If multiple author blocks are listed, each new block must be preceded by its own blank line. After the author blocks come the presentation slides or article sections, which can in turn have subsections. In Markdown-enabled present files, each slide or section begins with a "##" header line, subsections begin with a "###" header line, and so on. In legacy present files, each slide or section begins with a "*" header line, subsections begin with a "**" header line, and so on. In addition to the marked-up text in a section (or subsection), a present file can contain present command invocations, each of which begins with a dot, as in: .code x.go /^func main/,/^}/ .play y.go .image image.jpg .background image.jpg .iframe https://foo .link https://foo label .html file.html .caption _Gopher_ by [[https://instagram.com/reneefrench][Renee French]] Other than the commands, the text in a section is interpreted either as Markdown or as legacy present markup. # Markdown Syntax Markdown typically means the generic name for a family of similar markup languages. The specific variant used in present is CommonMark. See https://commonmark.org/help/tutorial/ for a quick tutorial. In Markdown-enabled present, section headings can end in {#name} to set the HTML anchor ID for the heading to "name". Lines beginning with "//" (outside of code blocks, of course) are treated as present comments and have no effect. Lines beginning with ": " are treated as speaker notes, described below. Example: # Title of Talk My Name 9 Mar 2020 me@example.com ## Title of Slide or Section (must begin with ##) Some Text ### Subsection {#anchor} - bullets - more bullets - a bullet continued on the next line #### Sub-subsection Some More text Preformatted text (code block) is indented (by one tab, or four spaces) Further Text, including command invocations. ## Section 2: Example formatting {#fmt} Formatting: _italic_ // A comment that is completely ignored. : Speaker notes. **bold** `program` Markup—_especially italic text_—can easily be overused. _Why use scoped\_ptr_? Use plain **\*ptr** instead. Visit [the Go home page](https://golang.org/). # Legacy Present Syntax Compared to Markdown, in legacy present slides/sections use "*" instead of "##", whole-line comments begin with "#" instead of "//", bullet lists can only contain single (possibly wrapped) text lines, and the font styling and link syntaxes are subtly different. Example: Title of Talk My Name 1 Jan 2013 me@example.com * Title of Slide or Section (must begin with *) Some Text ** Subsection - bullets - more bullets - a bullet continued on the next line (indented at least one space) *** Sub-subsection Some More text Preformatted text (code block) is indented (however you like) Further Text, including command invocations. * Section 2: Example formatting Formatting: _italic_ *bold* `program` Markup—_especially_italic_text_—can easily be overused. _Why_use_scoped__ptr_? Use plain ***ptr* instead. Visit [[https://golang.org][the Go home page]]. Within the input for plain text or lists, text bracketed by font markers will be presented in italic, bold, or program font. Marker characters are _ (italic), * (bold) and ` (program font). An opening marker must be preceded by a space or punctuation character or else be at start of a line; similarly, a closing marker must be followed by a space or punctuation character or else be at the end of a line. Unmatched markers appear as plain text. There must be no spaces between markers. Within marked text, a single marker character becomes a space and a doubled single marker quotes the marker character. Links can be included in any text with either explicit labels or the URL itself as the label. For example: [[url][label]] [[url]] # Command Invocations A number of special commands are available through invocations in the input text. Each such invocation contains a period as the first character on the line, followed immediately by the name of the function, followed by any arguments. A typical invocation might be .play demo.go /^func show/,/^}/ (except that the ".play" must be at the beginning of the line and not be indented as in this comment.) Here follows a description of the functions: code: Injects program source into the output by extracting code from files and injecting them as HTML-escaped <pre> blocks. The argument is a file name followed by an optional address that specifies what section of the file to display. The address syntax is similar in its simplest form to that of ed, but comes from sam and is more general. See https://plan9.io/sys/doc/sam/sam.html Table II for full details. The displayed block is always rounded out to a full line at both ends. If no pattern is present, the entire file is displayed. Any line in the program that ends with the four characters OMIT is deleted from the source before inclusion, making it easy to write things like .code test.go /START OMIT/,/END OMIT/ to find snippets like this tedious_code = boring_function() // START OMIT interesting_code = fascinating_function() // END OMIT and see only this: interesting_code = fascinating_function() Also, inside the displayed text a line that ends // HL will be highlighted in the display. A highlighting mark may have a suffix word, such as // HLxxx Such highlights are enabled only if the code invocation ends with "HL" followed by the word: .code test.go /^type Foo/,/^}/ HLxxx The .code function may take one or more flags immediately preceding the filename. This command shows test.go in an editable text area: .code -edit test.go This command shows test.go with line numbers: .code -numbers test.go play: The function "play" is the same as "code" but puts a button on the displayed source so the program can be run from the browser. Although only the selected text is shown, all the source is included in the HTML output so it can be presented to the compiler. link: Create a hyperlink. The syntax is 1 or 2 space-separated arguments. The first argument is always the HTTP URL. If there is a second argument, it is the text label to display for this link. .link https://golang.org golang.org image: The template uses the function "image" to inject picture files. The syntax is simple: 1 or 3 space-separated arguments. The first argument is always the file name. If there are more arguments, they are the height and width; both must be present, or substituted with an underscore. Replacing a dimension argument with the underscore parameter preserves the aspect ratio of the image when scaling. .image images/betsy.jpg 100 200 .image images/janet.jpg _ 300 video: The template uses the function "video" to inject video files. The syntax is simple: 2 or 4 space-separated arguments. The first argument is always the file name. The second argument is always the file content-type. If there are more arguments, they are the height and width; both must be present, or substituted with an underscore. Replacing a dimension argument with the underscore parameter preserves the aspect ratio of the video when scaling. .video videos/evangeline.mp4 video/mp4 400 600 .video videos/mabel.ogg video/ogg 500 _ background: The template uses the function "background" to set the background image for a slide. The only argument is the file name of the image. .background images/susan.jpg caption: The template uses the function "caption" to inject figure captions. The text after ".caption" is embedded in a figcaption element after processing styling and links as in standard text lines. .caption _Gopher_ by [[https://instagram.com/reneefrench][Renee French]] iframe: The function "iframe" injects iframes (pages inside pages). Its syntax is the same as that of image. html: The function html includes the contents of the specified file as unescaped HTML. This is useful for including custom HTML elements that cannot be created using only the slide format. It is your responsibility to make sure the included HTML is valid and safe. .html file.html # Presenter Notes Lines that begin with ": " are treated as presenter notes, in both Markdown and legacy present syntax. By default, presenter notes are collected but ignored. When running the present command with -notes, typing 'N' in your browser displaying your slides will create a second window displaying the notes. The second window is completely synced with the main window, except that presenter notes are only visible in the second window. Notes may appear anywhere within the slide text. For example: ## Title of slide Some text. : Presenter notes (first paragraph) Some more text. : Presenter notes (subsequent paragraph(s)) */ package present // import "golang.org/x/tools/present"
tools/present/doc.go/0
{ "file_path": "tools/present/doc.go", "repo_id": "tools", "token_count": 2893 }
775
# List ## - Item 1 on two lines. - Item 2. - Item 3. - Item 4 in list despite preceding blank line. - Item 5. --- <h1>List</h1> <section> <ul> <li> <p>Item 1 on two lines.</p> </li> <li> <p>Item 2.</p> </li> <li> <p>Item 3.</p> </li> <li> <p>Item 4 in list despite preceding blank line.</p> </li> <li> <p>Item 5.</p> </li> </ul> </section>
tools/present/testdata/list.md/0
{ "file_path": "tools/present/testdata/list.md", "repo_id": "tools", "token_count": 167 }
776
package A2 // This refactoring causes addition of "errors" import. // TODO(adonovan): fix: it should also remove "fmt". import myfmt "fmt" func example(n int) { myfmt.Errorf("%s", "") }
tools/refactor/eg/testdata/A2.go/0
{ "file_path": "tools/refactor/eg/testdata/A2.go", "repo_id": "tools", "token_count": 73 }
777
package F1 import "sync" func example(n int) { var x struct { mutex sync.RWMutex } var y struct { sync.RWMutex } type l struct { sync.RWMutex } var z struct { l } var a struct { *l } var b struct{ Lock func() } // Match x.mutex.RLock() // Match y.RLock() // Match indirect z.RLock() // Should be no match however currently matches due to: // https://golang.org/issue/8584 // Will start failing when this is fixed then just change golden to // No match pointer indirect // a.Lock() a.RLock() // No match b.Lock() }
tools/refactor/eg/testdata/F1.golden/0
{ "file_path": "tools/refactor/eg/testdata/F1.golden", "repo_id": "tools", "token_count": 226 }
778
package template const shouldFail = "no 'before' func found in template" func Before() {}
tools/refactor/eg/testdata/no_before.template/0
{ "file_path": "tools/refactor/eg/testdata/no_before.template", "repo_id": "tools", "token_count": 25 }
779
// 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 txtar_test import ( "io/fs" "strings" "testing" "testing/fstest" "golang.org/x/tools/txtar" ) func TestFS(t *testing.T) { var fstestcases = []struct { name, input, files string }{ { name: "empty", input: ``, files: "", }, { name: "one", input: ` -- one.txt -- one `, files: "one.txt", }, { name: "two", input: ` -- one.txt -- one -- two.txt -- two `, files: "one.txt two.txt", }, { name: "subdirectories", input: ` -- one.txt -- one -- 2/two.txt -- two -- 2/3/three.txt -- three -- 4/four.txt -- four `, files: "one.txt 2/two.txt 2/3/three.txt 4/four.txt", }, } for _, tc := range fstestcases { t.Run(tc.name, func(t *testing.T) { a := txtar.Parse([]byte(tc.input)) fsys, err := txtar.FS(a) if err != nil { t.Fatal(err) } files := strings.Fields(tc.files) if err := fstest.TestFS(fsys, files...); err != nil { t.Fatal(err) } for _, f := range a.Files { b, err := fs.ReadFile(fsys, f.Name) if err != nil { t.Errorf("ReadFile(%q) failed with error: %v", f.Name, err) } if got, want := string(b), string(f.Data); got != want { t.Errorf("ReadFile(%q) = %q; want %q", f.Name, got, want) } } }) } } func TestInvalid(t *testing.T) { invalidtestcases := []struct { name, want string input string }{ {"unclean file names", "invalid path", ` -- 1/../one.txt -- one -- 2/sub/../two.txt -- two `}, {"duplicate name", `cannot create fs.FS from txtar.Archive: duplicate path "1/2/one.txt"`, ` -- 1/2/one.txt -- one -- 1/2/one.txt -- two `}, {"file conflicts with directory", `duplicate path "1/2"`, ` -- 1/2 -- one -- 1/2/one.txt -- two `}, } for _, tc := range invalidtestcases { t.Run(tc.name, func(t *testing.T) { a := txtar.Parse([]byte(tc.input)) _, err := txtar.FS(a) if err == nil { t.Fatal("txtar.FS(...) succeeded; expected an error") } if got := err.Error(); !strings.Contains(got, tc.want) || tc.want == "" { t.Errorf("txtar.FS(...) got error %q; want %q", got, tc.want) } }) } } func TestModified(t *testing.T) { const input = ` -- one.txt -- one ` for _, mod := range []func(a *txtar.Archive){ func(a *txtar.Archive) { a.Files[0].Data = []byte("other") }, func(a *txtar.Archive) { a.Files[0].Name = "other" }, func(a *txtar.Archive) { a.Files = nil }, } { a := txtar.Parse([]byte(input)) if n := len(a.Files); n != 1 { t.Fatalf("txtar.Parse(%q) got %d files; expected 1", input, n) } fsys, err := txtar.FS(a) if err != nil { t.Fatal(err) } // Confirm we can open "one.txt". _, err = fsys.Open("one.txt") if err != nil { t.Fatal(err) } // Modify a to get ErrModified when opening "one.txt". mod(a) _, err = fsys.Open("one.txt") if err != txtar.ErrModified { t.Errorf("Open(%q) got error %s; want ErrModified", "one.txt", err) } } } func TestReadFile(t *testing.T) { const input = ` -- 1/one.txt -- one ` a := txtar.Parse([]byte(input)) fsys, err := txtar.FS(a) if err != nil { t.Fatal(err) } readfs := fsys.(fs.ReadFileFS) _, err = readfs.ReadFile("1") if err == nil { t.Errorf("ReadFile(%q) succeeded; expected an error when reading a directory", "1") } content, err := readfs.ReadFile("1/one.txt") if err != nil { t.Fatal(err) } want := "one\n" if got := string(content); want != got { t.Errorf("ReadFile(%q) = %q; want %q", "1/one.txt", got, want) } }
tools/txtar/fs_test.go/0
{ "file_path": "tools/txtar/fs_test.go", "repo_id": "tools", "token_count": 1680 }
780
# Go for Visual Studio Code [![Slack](https://img.shields.io/badge/slack-gophers-green.svg?style=flat)](https://gophers.slack.com/messages/vscode/) <!--TODO: We should add a badge for the build status or link to the build dashboard.--> [The VS Code Go extension](https://marketplace.visualstudio.com/items?itemName=golang.go) provides rich language support for the [Go programming language](https://go.dev/). ## Requirements * Visual Studio Code 1.75 or newer (or editors compatible with VS Code 1.75+ APIs) * Go 1.19 or newer. ## Quick Start Welcome! 👋🏻<br/> Whether you are new to Go or an experienced Go developer, we hope this extension fits your needs and enhances your development experience. 1. Install [Go](https://go.dev) 1.19 or newer if you haven't already. 1. Install the [VS Code Go extension]. 1. Open any Go file or go.mod file to automatically activate the extension. The [Go status bar](https://github.com/golang/vscode-go/wiki/ui) appears in the bottom right corner of the window and displays your Go version. 1. The extension depends on `go`, `gopls` (the Go language server), and optional tools depending on your settings. If `gopls` is missing, the extension will try to install it. The :zap: sign next to the Go version indicates the language server is running, and you are ready to go. <p align="center"> <img src="docs/images/gettingstarted.gif" width=75%> <br/> <em>(Install Missing Tools)</em> </p> You are ready to Go :-) &nbsp;&nbsp; 🎉🎉🎉 ## What's next * Explore more [features][full feature breakdown] of the VS Code Go extension. * View the [settings documentation](https://github.com/golang/vscode-go/wiki/settings) and [advanced topics](https://github.com/golang/vscode-go/wiki/advanced) to customize the extension. * View the [tools documentation](https://github.com/golang/vscode-go/wiki/tools) for a complete list of tools the VS Code Go extension depends on. You can install additional tools and update them by using "Go: Install/Update Tools". * Solve issues with the [general troubleshooting](https://github.com/golang/vscode-go/wiki/troubleshooting) and [debugging troubleshooting](https://github.com/golang/vscode-go/wiki/debugging#troubleshooting) guides. * [file an issue](https://github.com/golang/vscode-go/issues/new/choose) for problems with the extension. * Start a [GitHub discussion](https://github.com/golang/vscode-go/discussions) or get help on [Stack Overflow]. * Explore Go language resources on [go.dev/learn](https://go.dev/learn) and [golang.org/help](https://golang.org/help). If you are new to Go, [this article](https://golang.org/doc/code.html) provides the overview on Go code organization and basic `go` commands. Watch ["Getting started with VS Code Go"] for an explanation of how to build your first Go application using VS Code Go. ## Feature highlights * [IntelliSense] - Results appear for symbols as you type. * [Code navigation] - Jump to or peek at a symbol's declaration. * [Code editing] - Support for saved snippets, formatting and code organization, and automatic organization of imports. * [Diagnostics] - Build, vet, and lint errors shown as you type or on save. * Enhanced support for [testing] and [debugging] See the [full feature breakdown] for more details. <p align=center> <img src="docs/images/completion-signature-help.gif" width=75%> <br/> <em>(Code completion and Signature Help)</em> </p> In addition to integrated editing features, the extension provides several commands for working with Go files. You can access any of these by opening the Command Palette (`Ctrl+Shift+P` on Linux/Windows and `Cmd+Shift+P` on Mac), and then typing in the command name. See the [full list of commands](https://github.com/golang/vscode-go/wiki/commands#detailed-list) provided by this extension. <p align=center> <img src="docs/images/toggletestfile.gif" width=75%> <br/><em>(Toggle Test File)</em></p> **⚠️ Note**: the default syntax highlighting for Go files is provided by a [TextMate rule](https://github.com/worlpaker/go-syntax) embedded in VS Code, not by this extension. For better syntax highlighting, we recommend enabling [semantic highlighting](https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide) by turning on [Gopls' `ui.semanticTokens` setting](https://github.com/golang/vscode-go/wiki/settings#uisemantictokens). ``` "gopls": { "ui.semanticTokens": true } ``` ## Setting up your workspace The VS Code Go extension supports both `GOPATH` and Go modules modes. [Go modules](https://golang.org/ref/mod) are used to manage dependencies in recent versions of Go. Modules replace the `GOPATH`-based approach to specifying which source files are used in a given build, and they are the default build mode in go1.16+. We highly recommend Go development in module mode. If you are working on existing projects, please consider migrating to modules. Unlike the traditional `GOPATH` mode, module mode does not require the workspace to be located under `GOPATH` nor to use a specific structure. A module is defined by a directory tree of Go source files with a `go.mod` file in the tree's root directory. Your project may involve one or more modules. If you are working with multiple modules or uncommon project layouts, you will need to configure your workspace by using [Workspace Folders]. See the [Supported workspace layouts documentation] for more information. ## Preview version If you'd like to get early access to new features and bug fixes, you can use the nightly build of this extension. Learn how to install it in by reading the [Go Nightly documentation](https://github.com/golang/vscode-go/wiki/nightly). ## Telemetry VS Code Go extension relies on the [Go Telemetry](https://go.dev/doc/telemetry) to learn insights about the performance and stability of the extension and the language server (`gopls`). **Go Telemetry data uploading is disabled by default** and can be enabled with the following command: ``` go run golang.org/x/telemetry/cmd/gotelemetry@latest on ``` After telemetry is enabled, the language server will upload metrics and stack traces to [telemetry.go.dev](https://telemetry.go.dev). You can inspect what data is collected and can be uploaded by running: ``` go run golang.org/x/telemetry/cmd/gotelemetry@latest view ``` If we get enough adoption, this data can significantly advance the pace of the Go extension development, and help us meet a higher standard of reliability. For example: - Even with [semi-automated crash reports](https://github.com/golang/vscode-go/issues?q=is%3Aissue+is%3Aopen+label%3AautomatedReport) in VS Code, we've seen several crashers go unreported for weeks or months. - Even with [a suite of benchmarks](https://perf.golang.org/dashboard/?benchmark=all&repository=tools&branch=release-branch.go1.20), some performance regressions don't show up in our benchmark environment (such as the [completion bug](https://go.dev/issue/62665) mentioned below!). - Even with [lots of great ideas](https://github.com/golang/go/issues?q=is%3Aissue+is%3Aopen+label%3Agopls+label%3Afeaturerequest) for how to improve gopls, we have limited resources. Telemetry can help us identify which new features are most important, and which existing features aren't being used or aren't working well. These are just a few ways that telemetry can improve gopls. The [telemetry blog post series](https://research.swtch.com/telemetry-uses) contains many more. Go telemetry is designed to be transparent and privacy-preserving. Learn more at [https://go.dev/doc/telemetry](https://go.dev/doc/telemetry). ## Contributing We welcome your contributions and thank you for working to improve the Go development experience in VS Code. If you would like to help work on the VS Code Go extension, see our [contribution guide](https://github.com/golang/vscode-go/wiki/contributing) to learn how to build and run the VS Code Go extension locally and contribute to the project. ## Code of Conduct This project follows the [Go Community Code of Conduct](https://golang.org/conduct). If you encounter a conduct-related issue, please mail conduct@golang.org. ## License [MIT](LICENSE) [Stack Overflow]: https://stackoverflow.com/questions/tagged/go+visual-studio-code [`gopls`]: https://golang.org/s/gopls [`go`]: https://golang.org/cmd/go [Managing extensions in VS Code]: https://code.visualstudio.com/docs/editor/extension-gallery [VS Code Go extension]: https://marketplace.visualstudio.com/items?itemName=golang.go [Go installation guide]: https://golang.org/doc/install ["Getting started with VS Code Go"]: https://youtu.be/1MXIGYrMk80 [IntelliSense]: https://github.com/golang/vscode-go/wiki/features#intellisense [Code navigation]: https://github.com/golang/vscode-go/wiki/features#code-navigation [Code editing]: https://github.com/golang/vscode-go/wiki/features#code-editing [diagnostics]: https://github.com/golang/vscode-go/wiki/features#diagnostics [testing]: https://github.com/golang/vscode-go/wiki/features#run-and-test-in-the-editor [debugging]: https://github.com/golang/vscode-go/wiki/debugging#features [full feature breakdown]: https://github.com/golang/vscode-go/wiki/features [workspace documentation]: https://github.com/golang/tools/blob/master/gopls/doc/workspace.md [`Go: Install/Update Tools` command]: https://github.com/golang/vscode-go/wiki/commands#go-installupdate-tools [Supported workspace layouts documentation]: https://github.com/golang/tools/blob/master/gopls/doc/workspace.md [Workspace Folders]: https://code.visualstudio.com/docs/editor/multi-root-workspaces
vscode-go/README.md/0
{ "file_path": "vscode-go/README.md", "repo_id": "vscode-go", "token_count": 2937 }
781
# Contributing We welcome your contributions and thank you for working to improve the Go development experience in VS Code. This guide will explain the process of setting up your development environment to work on the VS Code Go extension, as well as the process of sending out your change for review. If you're interested in testing the master branch or pre-releases of the extension, please see the [Go Nightly documentation](nightly.md). Our canonical Git repository is located at https://go.googlesource.com/vscode-go and https://github.com/golang/vscode-go is a mirror. * [Before you start coding](#before-you-start-coding) * [Ask for help](#ask-for-help) * [Debug Adapter](#debug-adapter) * [Developing](#developing) * [Setup](#setup) * [Run](#run) * [Test](#test) * [Sideload](#sideload) * [Mail your change for review](#mail-your-change-for-review) * [Presubmit test in CI](#presubmit-test-in-ci) ## Before you start coding If you are interested in fixing a bug or contributing a feature, please [file an issue](https://github.com/golang/vscode-go/issues/new/choose) first. Wait for a project maintainer to respond before you spend time coding. If you wish to work on an existing issue, please add a comment saying so, as someone may already be working on it. A project maintainer may respond with advice on how to get started. If you're not sure which issues are available, search for issues with the [help wanted label](https://github.com/golang/vscode-go/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22). ### Ask for help The VS Code Go maintainers are reachable via the issue tracker and the [#vscode-dev] channel in the [Gophers Slack]. Please reach out on Slack with questions, suggestions, or ideas. If you have trouble getting started on an issue, we'd be happy to give pointers and advice. ### Language Server (`gopls`) Many of the language features like auto-completion, documentation, diagnostics are implemented by the Go language server ([`gopls`](https://pkg.go.dev/golang.org/x/tools/gopls)). This extension communicates with `gopls` using [vscode LSP client library](https://github.com/microsoft/vscode-languageserver-node) from [`language/goLanguageServer.ts`](https://github.com/golang/vscode-go/tree/master/src/language). For extending the language features or fixing bugs, please follow `gopls`'s [contribution guide](https://github.com/golang/tools/blob/master/gopls/doc/contributing.md). ### Debug Adapter (`dlv dap`) Debugging features are implemented by Delve (`dlv`) and its native DAP implementation ([`dlv dap`](https://github.com/go-delve/delve/blob/master/Documentation/api/dap/README.md)). * goDebugConfiguration.ts: where launch configuration massaging occurs. * goDebugFactory.ts: where a thin adapter that communicates with the `dlv dap` process is defined. * [github.com/go-delve/delve](https://github.com/go-delve/delve/tree/master/service/dap): where native DAP implementation in Delve exists. For extending the features of Delve, please follow `Delve` project's [contribution guide](https://github.com/go-delve/delve/blob/master/CONTRIBUTING.md). The debugging feature documentation has a dedicated section for tips for development (See ["Developing"](https://github.com/golang/vscode-go/blob/master/docs/debugging.md#developing) section). ## Developing ### Setup 1) Install [node](https://nodejs.org/en/). Note: make sure that you are using `npm v7` or higher. The file format for `package-lock.json` (changed significantly)[https://docs.npmjs.com/cli/v7/configuring-npm/package-lock-json#file-format] in `npm v7`. 2) Clone the repository, run `npm ci`, and open VS Code: ```bash git clone https://go.googlesource.com/vscode-go cd vscode-go/extension npm ci code . ``` #### Lint You can run `npm run lint` on the command-line to check for lint errors in your program. You can also use the [TSLint](https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-tslint-plugin) plugin to see errors as you code. ### Run To run the extension with your patch, open the Run view (`Ctrl+Shift+D` or `⌘+⇧+D`), select `Launch Extension`, and click the Play button (`F5`). This will open a new VS Code window with the title `[Extension Development Host]`. You can then open a folder that contains Go code and try out your changes. You can also set breakpoints to debug your change. If you make subsequent edits in the codebase, you can reload (`Ctrl+R` or `⌘+R`) the `[Extension Development Host]` instance of VS Code, which will load the new code. The debugger will automatically reattach. ## Test 1. `export GOPATH=/path/to/gopath/for/test` 2. `cd extension` -- most extension development work is done in the `extension` directory. 2. `go run tools/installtools/main.go` -- this will install all tools in the `GOPATH/bin` built from master/main. 3. There are currently two different types of tests in this repo: - `npm run unit-test`: this runs unit tests defined in `test/unit`. They are light-weight tests that don't require `vscode` APIs. - `npm run test`: this runs the integration tests defined in `test/integration` and `test/gopls`. They test logic that involve `vscode` APIs - which requires actually downloading & running Visual Studio Code (`code`) and loading the compiled extension/test code in it. 4. Before sending a CL, make sure to run - `npm run lint`: this runs linter. - `go run tools/generate.go -w=false -gopls=true`: this checks generated documentations are up-to-date. ### Testing Tips #### (1) Running only a subset of integration or unit tests: When running them from terminal: - Option 1: Utilize `MOCHA_GREP` environment variable. That is equivalent with [`mocha --grep` flag](https://mochajs.org/#command-line-usage) that runs tests matching the given string or regexp. E.g. `MOCHA_GREP=gopls npm run test` which runs all integration tests whose suite/test names contain `"gopls"`. - Option 2: modify the test source code and set the [`only`](https://mochajs.org/#exclusive-tests) or [`skip`](https://mochajs.org/#inclusive-tests) depending on your need. If necessary, you can also modify `test/integration/index.ts` or `test/gopls/index.ts` to include only the test files you want to focus on. Make sure to revert them before sending the changes for review. #### (2) Debugging tests from VS Code: `.vscode/launch.json` defines test launch configurations. To run the tests locally, open the Run view (`Ctrl+Shift+D`), select the relevant launch configuration, and hit the Play button (`F5`). Output and results of the tests, including any logging written with `console.log` will appear in the `DEBUG CONSOLE` tab. You can supply environment variables (e.g. `MOCHA_GREP`) by modifying the launch configuration entry's `env` property. - `Launch Unit Tests`: runs unit tests in `test/unit` (same as `npm run unit-test`) - `Launch Extension Tests`: runs tests in `test/integration` directory (similar to `npm run test` but runs only tests under `test/integration` directory) - `Launch Extension Tests with Gopls`: runs tests in `test/gopls directory (similar to `npm run test` but runs only tests under `test/gopls` directory) When you want to filter tests while debugging, utilize the `MOCAH_GREP` environment variable discussed previously - i.e., set the environment variable in the `env` property of the launch configuration. #### (3) Using different versions of tools. The tests will pick tools found from `GOPATH/bin` first. So, install the versions you want there. ## Running/Debugging the Extension Select the [`Launch Extension`](https://github.com/golang/vscode-go/blob/e2a7fb523acffea3427ad7e369c3b2abc30b775b/.vscode/launch.json#L13) configuration, and hit the Play button (`F5`). This will build the extension and start a new VS Code window with the title `"[Extension Development Host]"` that uses the newly built extension. This instance has the node.js debugger attached automatically. You can debug using the VS Code Debug UI of the main window (e.g. set breakpoints, inspect variables, step, etc) The VS Code window may have the folder or file used during your previous testing. If you want to change the folder during testing, close the folder by using "File > Close Folder", and open a new folder from the VS Code window under test. ### Debugging interaction with `gopls` When developing features in `gopls`, you may need to attach a debugger to `gopls` and configure the extension to connect to the `gopls` instance using [the gopls deamon mode](https://github.com/golang/tools/blob/master/gopls/doc/daemon.md). 1. Start a gopls in deamon mode: ``` gopls -listen=:37374 -logfile=auto -debug=:0 serve ``` Or, if you use vscode for gopls development, you can configure `launch.json` of the `x/tools/gopls` project: ``` ... { "name": "Launch Gopls", "type": "go", "request": "launch", "mode": "auto", "program": "${workspaceFolder}/gopls", "args": ["-listen=:37374", "-logfile=auto", "-debug=:0"], "cwd": "<... directory where you want to run your gopls from ...", } ... ``` 2. Start the extension debug session using the `Launch Extension` configuration. 3. Configure the settings.json of the project open in the `"[Extension Development Host]"` window to start `gopls` that connects to the gopls we started in the step 1. ``` "go.languageServerFlags": ["-remote=:37374", "-rpc.trace"] ``` ## Sideload After making changes to the extension, you may want to test it end-to-end instead of running it in debug mode. To do this, you can sideload the extension. 1. `cd` into the `extension` directory. 3. Install all dependencies by running `npm ci`. 4. Run `npx vsce package`. This will generate a file with a `.vsix` extension in your current directory. ```bash npm install -g vsce cd vscode-go npm ci vsce package ``` 5. Open a VS Code window, navigate to the Extensions view, and disable or uninstall the default Go extension. 6. Click on the "..." in the top-right corner, select "Install from VSIX...", and choose the generated VSIX file. Alternatively, you can run `code --install-extension path/to/go.vsix` or open the Command Palette and run the `Extensions: Install from VSIX...` command. ## Mail your change for review Once you have coded, built, and tested your change, it's ready for review! There are two ways to mail your change: (1) through [a GitHub pull request (PR)](https://golang.org/doc/contribute.html#sending_a_change_github), or (2) through a [Gerrit code review](https://golang.org/doc/contribute.html#sending_a_change_gerrit). In either case, code review will happen in [Gerrit](https://www.gerritcodereview.com/), which is used for all repositories in the Go project. We strongly recommend the Gerrit code review if you plan to send many changes. GitHub pull requests will be mirrored into Gerrit, so you can follow a more traditional GitHub workflow, but you will still have to look at Gerrit to read comments. The easiest way to start is by reading this [detailed guide for contributing to the Go project](https://golang.org/doc/contribute.html). Important things to note are: * You will need to sign the [Google CLA](https://golang.org/doc/contribute.html#cla). * Your commit message should follow the standards described on the [Commit Message Wiki](https://github.com/golang/go/wiki/CommitMessage). * Your change should include tests (if possible). Once you've sent out your change, a maintainer will take a look at your contribution within a few weeks. If you don't hear back, feel free to ping the issue or send a message to the [#vscode-dev] channel of the [Gophers Slack]. ### Presubmit Test in CI When you mail your CL or upload a new patch to an existing CL, *AND* you or a fellow contributor assigns the `Run-TryBot=+1` label in Gerrit, the test command defined in `build/all.bash` will run by `Kokoro`, which is Jenkins-like Google infrastructure for running Dockerized tests. `Kokoro` will post the result as a comment, and add its `TryBot-Result` vote after each test run completes. To force a re-run of the Kokoro CI, add comment `kokoro rerun` to the CL. [#vscode-dev]: https://gophers.slack.com/archives/CUWGEKH5Z [Gophers Slack]: https://invite.slack.golangbridge.org/
vscode-go/docs/contributing.md/0
{ "file_path": "vscode-go/docs/contributing.md", "repo_id": "vscode-go", "token_count": 3662 }
782
# Extension UI ## Using The Go Status Bar The Go status bar appears in the lower right of the extension window, next to the Editor Language status bar item. Clicking the Go status bar brings up a menu that provides easy access to see and update important information about your Go project. This includes information about the Go environment, the current Go version, the `gopls` trace, and about the current module. <div style="text-align: center;"><img src="images/gostatusbar.png" alt="vscode extension after Go status bar item is clicked" style="width:75%" > </div> ## Using The Language Status Bar The Language status bar shows status of dependency tools installation or availability of newly released Go versions. <div style="text-align: center;"><img src="images/languagestatusbar.png" alt="Go language status bar" style="width:75%" > </div> ### Go Environment The `Go Locate Configured Go Tools` command will display the configured GOPATH, GOROOT, tool locations and the results of `go env` in the output window. ### Managing Your Go Version You can view the current Go version by looking at the status bar item in the bottom left corner of VS Code. Clicking this button and selecting `Choose Go Environment` will present you with a menu from which you can select any version of Go that exists in your $HOME/sdk directory or on <https://golang.org/dl>. This command is also available through the command pallette using `Go: Choose Go Environment`. If you are using go1.21 or newer, you can control your Go version using the `GOTOOLCHAIN` environment variable. See https://go.dev/doc/toolchain for more information. To tell the extension to use a different `GOTOOLCHAIN`, use the `go.toolsEnvVars` setting or the Go explorer view. ``` "go.toolsEnvVars": { "GOTOOLCHAIN": "go1.21.0+auto" } ``` You will need to reload the window after updating this setting. We are working on improving the version switch workflow. Previously, the `go.goroot` and `go.alternateTools` settings controlled the Go version used by VS Code Go. If you have configured these settings, they are no longer needed and should be deleted. ### Installing a New Go Version After selecting any Go version that has not yet been installed (such as Go 1.14.6 in the screenshot above), the binary will be automatically installed in $HOME/sdk and put to use in your environment. Once the download completes, VS Code Go will make use of this new Go version. ### Language Server Status `gopls` is the official Go [language server](https://langserver.org/) developed by the Go team. It was developed in response to the release of Go modules, and it is the recommended approach when working with Go modules in VS Code. When `gopls` is enabled, :zap: is displayed next to the Go version in the Go status bar and the `gopls` version is displayed in the menu. Selecting `Open 'gopls' trace` will open the trace of the `gopls` server in the output window. Please include this trace when filing an issue related to the extension and `gopls` is enabled. ### Modules Status When modules are enabled for the file you have open, you can navigate to the `go.mod` file for the project using the menu. If you do not see the `Open go.mod` item, then the extension does not think the file you have open belongs to a module. More information about [using Go modules](https://go.dev/blog/using-go-modules ) is available on the Go blog. ## Go Explorer View The view displays the go environment variables (`go env`) that are applied to the file open in the editor. You can customize the list by "Go: Edit Workspace" command (pencil icon), and update modifiable environment variables through this view. It displays required [tools](tools.md) and their location/version info, too. <div style="text-align: center;"><img src="images/goexplorer.png" alt="Go explorer view" style="width:75%" > </div>
vscode-go/docs/ui.md/0
{ "file_path": "vscode-go/docs/ui.md", "repo_id": "vscode-go", "token_count": 989 }
783
/*--------------------------------------------------------- * Copyright 2020 The Go Authors. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ // This script will be run within the webview itself // It cannot access the main VS Code APIs directly. (function () { const vscode = acquireVsCodeApi(); const commands = document.querySelectorAll('.Command'); for (let i = 0; i < commands.length; i++) { const elem = commands[i]; const msg = JSON.parse(JSON.stringify(elem.dataset)); elem.addEventListener('click', () => { vscode.postMessage(msg); }) } }());
vscode-go/extension/media/welcome.js/0
{ "file_path": "vscode-go/extension/media/welcome.js", "repo_id": "vscode-go", "token_count": 192 }
784
/*--------------------------------------------------------- * 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. *--------------------------------------------------------*/ // This file contains constants that need to change when building Nightly or Go2Go. // // For example, we replace this file with the version in the build/nightly. // Make sure to reflect any changes in this file to build/nightly/const.ts. export const extensionId = 'golang.go';
vscode-go/extension/src/const.ts/0
{ "file_path": "vscode-go/extension/src/const.ts", "repo_id": "vscode-go", "token_count": 130 }
785
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ 'use strict'; import vscode = require('vscode'); import { getGoConfig } from './config'; import { getCurrentGoPath, getToolsGopath, resolvePath, substituteEnv } from './util'; import { dirExists } from './utils/pathUtils'; import { getFromGlobalState, updateGlobalState } from './stateUtils'; import { outputChannel } from './goStatus'; // toolInstallationEnvironment returns the environment in which tools should // be installed. It always returns a new object. export function toolInstallationEnvironment(): NodeJS.Dict<string> { const env = newEnvironment(); // If the go.toolsGopath is set, use its value as the GOPATH for `go` processes. // Else use the Current Gopath let toolsGopath = getToolsGopath(); if (toolsGopath) { // User has explicitly chosen to use toolsGopath, so ignore GOBIN. env['GOBIN'] = ''; } else { toolsGopath = getCurrentGoPath(); } if (!toolsGopath) { const msg = 'Cannot install Go tools. Set either go.gopath or go.toolsGopath in settings.'; vscode.window.showInformationMessage(msg, 'Open User Settings', 'Open Workspace Settings').then((selected) => { switch (selected) { case 'Open User Settings': vscode.commands.executeCommand('workbench.action.openGlobalSettings'); break; case 'Open Workspace Settings': vscode.commands.executeCommand('workbench.action.openWorkspaceSettings'); break; } }); return {}; } env['GOPATH'] = toolsGopath; // Explicitly set 'auto' so tools that require // a newer toolchain can be built. // We don't use unset, but unconditionally set this env var // since some users may change the env var using GOENV, // GOROOT/.goenv, or toolchain modification. env['GOTOOLCHAIN'] = 'auto'; // Unset env vars that would affect tool build process: 'GOROOT', 'GOOS', 'GOARCH', ... // Tool installation should be done for the host OS/ARCH (GOHOSTOS/GOHOSTARCH) with // the default setup. delete env['GOOS']; delete env['GOARCH']; delete env['GOROOT']; delete env['GOFLAGS']; delete env['GOENV']; delete env['GO111MODULE']; // we require module mode (default) for tools installation. return env; } // toolExecutionEnvironment returns the environment in which tools should // be executed. It always returns a new object. export function toolExecutionEnvironment(uri?: vscode.Uri, addProcessEnv = true): NodeJS.Dict<string> { const env = newEnvironment(uri, addProcessEnv); const gopath = getCurrentGoPath(uri); if (gopath) { env['GOPATH'] = gopath; } // Remove json flag (-json or --json=<any>) from GOFLAGS because it will effect to result format of the execution if (env['GOFLAGS'] && env['GOFLAGS'].includes('-json')) { env['GOFLAGS'] = env['GOFLAGS'].replace(/(^|\s+)-?-json[^\s]*/g, ''); outputChannel.debug(`removed -json from GOFLAGS: ${env['GOFLAGS']}`); } return env; } function newEnvironment(uri?: vscode.Uri, addProcessEnv = true): NodeJS.Dict<string> { const toolsEnvVars = getGoConfig(uri)['toolsEnvVars']; const env = addProcessEnv ? Object.assign({}, process.env) : {}; if (toolsEnvVars && typeof toolsEnvVars === 'object') { Object.keys(toolsEnvVars).forEach( (key) => (env[key] = typeof toolsEnvVars[key] === 'string' ? resolvePath(substituteEnv(toolsEnvVars[key])) : toolsEnvVars[key]) ); } // The http.proxy setting takes precedence over environment variables. const httpProxy = vscode.workspace.getConfiguration('http', null).get('proxy'); if (httpProxy && typeof httpProxy === 'string') { env['http_proxy'] = httpProxy; env['HTTP_PROXY'] = httpProxy; env['https_proxy'] = httpProxy; env['HTTPS_PROXY'] = httpProxy; } return env; } // set GOROOT env var. If necessary, shows a warning. export async function setGOROOTEnvVar(configGOROOT: string) { if (!configGOROOT) { return; } const goroot = configGOROOT ? resolvePath(substituteEnv(configGOROOT)) : undefined; const currentGOROOT = process.env['GOROOT']; if (goroot === currentGOROOT) { return; } if (!(await dirExists(goroot ?? ''))) { vscode.window.showWarningMessage(`go.goroot setting is ignored. ${goroot} is not a valid GOROOT directory.`); return; } const neverAgain = { title: "Don't Show Again" }; const ignoreGOROOTSettingWarningKey = 'ignoreGOROOTSettingWarning'; const ignoreGOROOTSettingWarning = getFromGlobalState(ignoreGOROOTSettingWarningKey); if (!ignoreGOROOTSettingWarning) { vscode.window .showInformationMessage( `"go.goroot" setting (${goroot}) will be applied and set the GOROOT environment variable.`, neverAgain ) .then((result) => { if (result === neverAgain) { updateGlobalState(ignoreGOROOTSettingWarningKey, true); } }); } outputChannel.debug( `setting GOROOT = ${goroot} (old value: ${currentGOROOT}) because "go.goroot": "${configGOROOT}"` ); if (goroot) { process.env['GOROOT'] = goroot; } else { delete process.env.GOROOT; } }
vscode-go/extension/src/goEnv.ts/0
{ "file_path": "vscode-go/extension/src/goEnv.ts", "repo_id": "vscode-go", "token_count": 1777 }
786
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-explicit-any */ /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ 'use strict'; import vscode = require('vscode'); import { CancellationToken, CodeLens, TextDocument } from 'vscode'; import { getGoConfig } from './config'; import { GoBaseCodeLensProvider } from './goBaseCodelens'; import { GoDocumentSymbolProvider } from './goDocumentSymbols'; import { getBenchmarkFunctions, getTestFunctions } from './testUtils'; import { GoExtensionContext } from './context'; import { GO_MODE } from './goMode'; export class GoRunTestCodeLensProvider extends GoBaseCodeLensProvider { static activate(ctx: vscode.ExtensionContext, goCtx: GoExtensionContext) { const testCodeLensProvider = new this(goCtx); ctx.subscriptions.push(vscode.languages.registerCodeLensProvider(GO_MODE, testCodeLensProvider)); ctx.subscriptions.push( vscode.workspace.onDidChangeConfiguration(async (e: vscode.ConfigurationChangeEvent) => { if (!e.affectsConfiguration('go')) { return; } const updatedGoConfig = getGoConfig(); if (updatedGoConfig['enableCodeLens']) { testCodeLensProvider.setEnabled(updatedGoConfig['enableCodeLens']['runtest']); } }) ); } constructor(private readonly goCtx: GoExtensionContext) { super(); } private readonly benchmarkRegex = /^Benchmark.+/; public async provideCodeLenses(document: TextDocument, token: CancellationToken): Promise<CodeLens[]> { if (!this.enabled) { return []; } const config = getGoConfig(document.uri); const codeLensConfig = config.get<{ [key: string]: any }>('enableCodeLens'); const codelensEnabled = codeLensConfig ? codeLensConfig['runtest'] : false; if (!codelensEnabled || !document.fileName.endsWith('_test.go')) { return []; } const codelenses = await Promise.all([ this.getCodeLensForPackage(document, token), this.getCodeLensForFunctions(document, token) ]); return ([] as CodeLens[]).concat(...codelenses); } private async getCodeLensForPackage(document: TextDocument, token: CancellationToken): Promise<CodeLens[]> { const documentSymbolProvider = GoDocumentSymbolProvider(this.goCtx); const symbols = await documentSymbolProvider.provideDocumentSymbols(document); if (!symbols || symbols.length === 0) { return []; } const pkg = symbols[0]; if (!pkg) { return []; } const range = pkg.range; const packageCodeLens = [ new CodeLens(range, { title: 'run package tests', command: 'go.test.package' }), new CodeLens(range, { title: 'run file tests', command: 'go.test.file' }) ]; if (pkg.children.some((sym) => sym.kind === vscode.SymbolKind.Function && this.benchmarkRegex.test(sym.name))) { packageCodeLens.push( new CodeLens(range, { title: 'run package benchmarks', command: 'go.benchmark.package' }), new CodeLens(range, { title: 'run file benchmarks', command: 'go.benchmark.file' }) ); } return packageCodeLens; } private async getCodeLensForFunctions(document: TextDocument, token: CancellationToken): Promise<CodeLens[]> { const testPromise = async (): Promise<CodeLens[]> => { const codelens: CodeLens[] = []; const testFunctions = await getTestFunctions(this.goCtx, document, token); if (!testFunctions) { return codelens; } const simpleRunRegex = /t.Run\("([^"]+)",/; for (const f of testFunctions) { const functionName = f.name; codelens.push( new CodeLens(f.range, { title: 'run test', command: 'go.test.cursor', arguments: [{ functionName }] }), new CodeLens(f.range, { title: 'debug test', command: 'go.debug.cursor', arguments: [{ functionName }] }) ); for (let i = f.range.start.line; i < f.range.end.line; i++) { const line = document.lineAt(i); const simpleMatch = line.text.match(simpleRunRegex); // BUG: this does not handle nested subtests. This should // be solved once codelens is handled by gopls and not by // vscode. if (simpleMatch) { const subTestName = simpleMatch[1]; codelens.push( new CodeLens(line.range, { title: 'run test', command: 'go.subtest.cursor', arguments: [{ functionName, subTestName }] }), new CodeLens(line.range, { title: 'debug test', command: 'go.debug.subtest.cursor', arguments: [{ functionName, subTestName }] }) ); } } } return codelens; }; const benchmarkPromise = async (): Promise<CodeLens[]> => { const benchmarkFunctions = await getBenchmarkFunctions(this.goCtx, document, token); if (!benchmarkFunctions) { return []; } const codelens: CodeLens[] = []; for (const f of benchmarkFunctions) { codelens.push( new CodeLens(f.range, { title: 'run benchmark', command: 'go.benchmark.cursor', arguments: [{ functionName: f.name }] }) ); codelens.push( new CodeLens(f.range, { title: 'debug benchmark', command: 'go.debug.cursor', arguments: [{ functionName: f.name }] }) ); } return codelens; }; const codelenses = await Promise.all([testPromise(), benchmarkPromise()]); return ([] as CodeLens[]).concat(...codelenses); } }
vscode-go/extension/src/goRunTestCodelens.ts/0
{ "file_path": "vscode-go/extension/src/goRunTestCodelens.ts", "repo_id": "vscode-go", "token_count": 2157 }
787
/*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ import path = require('path'); import vscode = require('vscode'); import { CommandFactory } from './commands'; import { getGoConfig } from './config'; import { toolExecutionEnvironment } from './goEnv'; import { diagnosticsStatusBarItem, outputChannel } from './goStatus'; import { getGoVersion, getWorkspaceFolderPath, handleDiagnosticErrors, ICheckResult, resolvePath, runTool } from './util'; /** * Runs go vet in the current package or workspace. */ export function vetCode(vetWorkspace?: boolean): CommandFactory { return (ctx, goCtx) => () => { const editor = vscode.window.activeTextEditor; if (!editor && !vetWorkspace) { vscode.window.showInformationMessage('No editor is active, cannot find current package to vet'); return; } if (editor?.document.languageId !== 'go' && !vetWorkspace) { vscode.window.showInformationMessage( 'File in the active editor is not a Go file, cannot find current package to vet' ); return; } const documentUri = editor?.document.uri; const goConfig = getGoConfig(documentUri); outputChannel.appendLine('Vetting...'); diagnosticsStatusBarItem.show(); diagnosticsStatusBarItem.text = 'Vetting...'; goVet(documentUri, goConfig, vetWorkspace) .then((warnings) => { handleDiagnosticErrors(goCtx, editor?.document, warnings, goCtx.vetDiagnosticCollection); diagnosticsStatusBarItem.hide(); }) .catch((err) => { vscode.window.showInformationMessage('Error: ' + err); diagnosticsStatusBarItem.text = 'Vetting Failed'; }); }; } /** * Runs go vet or go tool vet and presents the output in the 'Go' channel and in the diagnostic collections. * * @param fileUri Document uri. * @param goConfig Configuration for the Go extension. * @param vetWorkspace If true vets code in all workspace. */ export async function goVet( fileUri: vscode.Uri | undefined, goConfig: vscode.WorkspaceConfiguration, vetWorkspace?: boolean ): Promise<ICheckResult[]> { epoch++; const closureEpoch = epoch; if (tokenSource) { if (running) { tokenSource.cancel(); } tokenSource.dispose(); } tokenSource = new vscode.CancellationTokenSource(); const currentWorkspace = getWorkspaceFolderPath(fileUri); const cwd = vetWorkspace && currentWorkspace ? currentWorkspace : (fileUri && path.dirname(fileUri.fsPath)) ?? ''; if (!path.isAbsolute(cwd)) { return Promise.resolve([]); } const vetFlags: string[] = goConfig['vetFlags'] || []; const vetEnv = toolExecutionEnvironment(); const args: string[] = []; vetFlags.forEach((flag) => { if (flag.startsWith('--vettool=') || flag.startsWith('-vettool=')) { let vetToolPath = flag.substr(flag.indexOf('=') + 1).trim(); if (!vetToolPath) { return; } vetToolPath = resolvePath(vetToolPath); args.push(`${flag.substr(0, flag.indexOf('=') + 1)}${vetToolPath}`); return; } args.push(flag); }); const goVersion = await getGoVersion(); const tagsArg = []; if (goConfig['buildTags'] && vetFlags.indexOf('-tags') === -1) { tagsArg.push('-tags'); tagsArg.push(goConfig['buildTags']); } let vetArgs = ['vet', ...args, ...tagsArg, vetWorkspace ? './...' : '.']; if (goVersion && goVersion.lt('1.10') && args.length) { vetArgs = ['tool', 'vet', ...args, ...tagsArg, '.']; } outputChannel.appendLine(`Starting "go vet" under the folder ${cwd}`); running = true; return runTool(vetArgs, cwd, 'warning', true, '', vetEnv, false, tokenSource.token).then((result) => { if (closureEpoch === epoch) { running = false; } return result; }); } let epoch = 0; let tokenSource: vscode.CancellationTokenSource; let running = false;
vscode-go/extension/src/goVet.ts/0
{ "file_path": "vscode-go/extension/src/goVet.ts", "repo_id": "vscode-go", "token_count": 1325 }
788
/* eslint-disable @typescript-eslint/no-explicit-any */ /*--------------------------------------------------------- * Copyright 2020 The Go Authors. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------*/ import { ChildProcess } from 'child_process'; import kill = require('tree-kill'); // Kill a process and its children, returning a promise. export function killProcessTree(p: ChildProcess, logger: (...args: any[]) => void = console.log): Promise<void> { if (!p || !p.pid || p.exitCode !== null) { return Promise.resolve(); } return new Promise((resolve) => { kill(p.pid, (err) => { if (err) { logger(`Error killing process ${p.pid}: ${err}`); } resolve(); }); }); }
vscode-go/extension/src/utils/processUtils.ts/0
{ "file_path": "vscode-go/extension/src/utils/processUtils.ts", "repo_id": "vscode-go", "token_count": 241 }
789
/*--------------------------------------------------------- * 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 { sanitizeGoplsTrace } from '../../src/language/goLanguageServer'; suite('gopls issue report tests', () => { test('sanitize user trace', () => { interface TestCase { name: string; in: string; want?: string; wantReason?: string; } const testCases: TestCase[] = [ { name: 'panic trace', in: traceFromIssueGo41435, want: sanitizedTraceFromIssueGo41435 }, { name: 'initialization error message', in: traceFromIssueVSCodeGo572LSP317, want: sanitizedTraceFromIssueVSCodeGo572LSP317 }, { name: 'panic trace 2024 March', in: trace2024MarchPanic, want: sanitizedTrace2024MarchPanic }, { name: 'incomplete panic trace', in: 'panic: \ntruncated\n', want: 'panic: \ntruncated\n' }, { name: 'incomplete initialization error message', in: 'Secret Starting client failed.\nAnoter Secret\n', wantReason: 'unrecognized crash pattern' } ]; testCases.map((tc: TestCase) => { const { sanitizedLog, failureReason } = sanitizeGoplsTrace(tc.in); assert.strictEqual( JSON.stringify(sanitizedLog), JSON.stringify(tc.want), `sanitizeGoplsTrace(${tc.name}) returned unexpected sanitizedLog result - ${sanitizedLog}` ); assert.strictEqual( failureReason, tc.wantReason, `sanitizeGoplsTrace(${tc.name}) returned unexpected failureReason result` ); }); }); }); const traceFromIssueGo41435 = ` [Info - 12:50:16 PM] 2020/09/16 12:50:16 go env for /Users/Gopher/go/src/project (root /Users/Gopher/go/src/project) (valid build configuration = true) (build flags: []) GONOSUMDB= GOPROXY=http://172.26.1.9:5000 GOROOT=/opt/local/lib/go GOSUMDB=off GOCACHE=/Users/Gopher/Library/Caches/go-build GOMODCACHE= GOPRIVATE= GO111MODULE= GOINSECURE= GOPATH=/Users/Gopher/go GOFLAGS= GOMOD= GONOPROXY= [Info - 12:50:16 PM] 2020/09/16 12:50:16 go/packages.Load snapshot=0 directory=/Users/Gopher/go/src/project query=[./... builtin] packages=2 [Info - 12:50:16 PM] 2020/09/16 12:50:16 go/packages.Load snapshot=1 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=0 [Error - 12:50:16 PM] 2020/09/16 12:50:16 reloadOrphanedFiles: failed to load: no packages returned: packages.Load error query=[file:///Users/Gopher/go/src/project/main.go] [Info - 12:50:16 PM] 2020/09/16 12:50:16 go/packages.Load snapshot=1 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=0 [Error - 12:50:16 PM] 2020/09/16 12:50:16 DocumentSymbols failed: getting file for DocumentSymbols: no packages returned: packages.Load error URI=file:///Users/Gopher/go/src/project/main.go [Info - 12:50:16 PM] 2020/09/16 12:50:16 go/packages.Load snapshot=1 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=0 [Error - 12:50:16 PM] 2020/09/16 12:50:16 failed to compute document links: no packages returned: packages.Load error URI=file:///Users/Gopher/go/src/project/main.go [Info - 12:50:18 PM] 2020/09/16 12:50:18 go/packages.Load snapshot=2 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:18 PM] 2020/09/16 12:50:18 go/packages.Load snapshot=2 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:18 PM] 2020/09/16 12:50:18 go/packages.Load snapshot=2 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:18 PM] 2020/09/16 12:50:18 go/packages.Load snapshot=2 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Error - 12:50:19 PM] Request textDocument/completion failed. Message: invalid pos Code: 0 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=10 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=10 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=10 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=10 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=11 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=11 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=11 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=11 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=12 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=12 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=12 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=12 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=13 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=13 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=13 package_path="command-line-arguments" files=[/Users/Gopher/go/src/project/main.go] [Info - 12:50:20 PM] 2020/09/16 12:50:20 go/packages.Load snapshot=13 directory=/Users/Gopher/go/src/project query=[file=/Users/Gopher/go/src/project/main.go] packages=1 [Info - 12:50:26 PM] 2020/09/16 12:50:26 go/packages.Load snapshot=17 directory=/Users/Gopher/go/src/project query=[./... builtin] packages=2 panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x16cc8a8] goroutine 1011 [running]: golang.org/x/tools/internal/lsp/mod.vendorLens(0x1ae5540, 0xc000385480, 0x1af9ac0, 0xc0007c8dc0, 0x277eae8, 0xc000504f80, 0xc00032ff80, 0xc000332600, 0xb, 0x10, ...) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/lsp/mod/code_lens.go:129 +0x158 golang.org/x/tools/internal/lsp.(*Server).codeLens(0xc0002d72c0, 0x1ae5540, 0xc000385480, 0xc0006eaab0, 0x0, 0x0, 0x0, 0x0, 0x0) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/lsp/code_lens.go:38 +0x4a1 golang.org/x/tools/internal/lsp.(*Server).CodeLens(0xc0002d72c0, 0x1ae5540, 0xc000385480, 0xc0006eaab0, 0xc0006eaab0, 0x0, 0x0, 0xc0007e87c0, 0x1ae5600) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/lsp/server_gen.go:16 +0x4d golang.org/x/tools/internal/lsp/protocol.serverDispatch(0x1ae5540, 0xc000385480, 0x1b009e0, 0xc0002d72c0, 0xc0006eaa80, 0x1ae5780, 0xc0003853c0, 0x0, 0x0, 0x0) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/lsp/protocol/tsserver.go:325 +0x263d golang.org/x/tools/internal/lsp/protocol.ServerHandler.func1(0x1ae5540, 0xc000385480, 0xc0006eaa80, 0x1ae5780, 0xc0003853c0, 0x0, 0xbfd08444a6de7080) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/lsp/protocol/protocol.go:63 +0xc0 golang.org/x/tools/internal/lsp/lsprpc.handshaker.func1(0x1ae5540, 0xc000385480, 0xc0006eaa80, 0x1ae5780, 0xc0003853c0, 0x0, 0x0) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/lsp/lsprpc/lsprpc.go:557 +0x420 golang.org/x/tools/internal/jsonrpc2.MustReplyHandler.func1(0x1ae5540, 0xc000385480, 0xc000445080, 0x1ae5780, 0xc0003853c0, 0xc0002a04b7, 0x20) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/jsonrpc2/handler.go:35 +0xd3 golang.org/x/tools/internal/jsonrpc2.AsyncHandler.func1.2(0xc00021ac60, 0xc0007b7980, 0xc000326d20, 0x1ae5540, 0xc000385480, 0xc000445080, 0x1ae5780, 0xc0003853c0) /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/jsonrpc2/handler.go:103 +0x86 created by golang.org/x/tools/internal/jsonrpc2.AsyncHandler.func1 /Users/Gopher/go/pkg/mod/golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940/internal/jsonrpc2/handler.go:100 +0x171 [Info - 12:50:26 PM] Connection to server got closed. Server will restart. [Error - 12:50:26 PM] Request textDocument/codeLens failed. Error: Connection got disposed. at Object.dispose (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:13824:25) at Object.dispose (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:10459:35) at LanguageClient.handleConnectionClosed (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:12694:42) at LanguageClient.handleConnectionClosed (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:70282:15) at closeHandler (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:12681:18) at CallbackList.invoke (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24072:39) at Emitter.fire (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24131:36) at closeHandler (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:13160:26) at CallbackList.invoke (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24072:39) at Emitter.fire (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24131:36) at StreamMessageReader.fireClose (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:28055:27) at Socket. (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:28095:46) at Socket.emit (events.js:208:15) at Pipe. (net.js:588:12) [Error - 12:50:26 PM] Request textDocument/foldingRange failed. Error: Connection got disposed. at Object.dispose (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:13824:25) at Object.dispose (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:10459:35) at LanguageClient.handleConnectionClosed (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:12694:42) at LanguageClient.handleConnectionClosed (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:70282:15) at closeHandler (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:12681:18) at CallbackList.invoke (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24072:39) at Emitter.fire (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24131:36) at closeHandler (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:13160:26) at CallbackList.invoke (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24072:39) at Emitter.fire (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:24131:36) at StreamMessageReader.fireClose (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:28055:27) at Socket. (/Users/Gopher/.vscode/extensions/golang.go-0.16.2/dist/goMain.js:28095:46) at Socket.emit (events.js:208:15) at Pipe. (net.js:588:12) [Info - 12:50:26 PM] 2020/09/16 12:50:26 Build info golang.org/x/tools/gopls v0.5.0 golang.org/x/tools/gopls@v0.5.0 h1:XEmO9RylgmaXp33iGrWfCGopVYDGBmLy+KmsIsfIo8Y= github.com/BurntSushi/toml@v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/google/go-cmp@v0.5.1 h1:JFrFEBb2xKufg6XkJsJr+WbKb4FQlURi5RUcBveYu9k= github.com/sergi/go-diff@v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= golang.org/x/mod@v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= golang.org/x/sync@v0.0.0-20200625203802-6e8e738ad208 h1:qwRHBd0NqMbJxfbotnDhm2ByMI1Shq4Y6oRJo21SGJA= golang.org/x/tools@v0.0.0-20200914163123-ea50a3c84940 h1:151ExL+g/k/wnhOqV+O1OliaTi0FR2UxQEEcpAhzzw8= golang.org/x/xerrors@v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= honnef.co/go/tools@v0.0.1-2020.1.5 h1:nI5egYTGJakVyOryqLs1cQO5dO0ksin5XXs2pspk75k= mvdan.cc/gofumpt@v0.0.0-20200802201014-ab5a8192947d h1:t8TAw9WgTLghti7RYkpPmqk4JtQ3+wcP5GgZqgWeWLQ= mvdan.cc/xurls/v2@v2.2.0 h1:NSZPykBXJFCetGZykLAxaL6SIpvbVy/UFEniIfHAa8A=`; const sanitizedTraceFromIssueGo41435 = `panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x16cc8a8] goroutine 1011 [running]: golang.org/x/tools/internal/lsp/mod.vendorLens(0x1ae5540, 0xc000385480, 0x1af9ac0, 0xc0007c8dc0, 0x277eae8, 0xc000504f80, 0xc00032ff80, 0xc000332600, 0xb, 0x10, ...) code_lens.go:129 +0x158 golang.org/x/tools/internal/lsp.(*Server).codeLens(0xc0002d72c0, 0x1ae5540, 0xc000385480, 0xc0006eaab0, 0x0, 0x0, 0x0, 0x0, 0x0) code_lens.go:38 +0x4a1 golang.org/x/tools/internal/lsp.(*Server).CodeLens(0xc0002d72c0, 0x1ae5540, 0xc000385480, 0xc0006eaab0, 0xc0006eaab0, 0x0, 0x0, 0xc0007e87c0, 0x1ae5600) server_gen.go:16 +0x4d golang.org/x/tools/internal/lsp/protocol.serverDispatch(0x1ae5540, 0xc000385480, 0x1b009e0, 0xc0002d72c0, 0xc0006eaa80, 0x1ae5780, 0xc0003853c0, 0x0, 0x0, 0x0) tsserver.go:325 +0x263d golang.org/x/tools/internal/lsp/protocol.ServerHandler.func1(0x1ae5540, 0xc000385480, 0xc0006eaa80, 0x1ae5780, 0xc0003853c0, 0x0, 0xbfd08444a6de7080) protocol.go:63 +0xc0 golang.org/x/tools/internal/lsp/lsprpc.handshaker.func1(0x1ae5540, 0xc000385480, 0xc0006eaa80, 0x1ae5780, 0xc0003853c0, 0x0, 0x0) lsprpc.go:557 +0x420 golang.org/x/tools/internal/jsonrpc2.MustReplyHandler.func1(0x1ae5540, 0xc000385480, 0xc000445080, 0x1ae5780, 0xc0003853c0, 0xc0002a04b7, 0x20) handler.go:35 +0xd3 golang.org/x/tools/internal/jsonrpc2.AsyncHandler.func1.2(0xc00021ac60, 0xc0007b7980, 0xc000326d20, 0x1ae5540, 0xc000385480, 0xc000445080, 0x1ae5780, 0xc0003853c0) handler.go:103 +0x86 created by golang.org/x/tools/internal/jsonrpc2.AsyncHandler.func1 handler.go:100 +0x171 `; const traceFromIssueVSCodeGo572LSP317 = ` [Error - 12:20:35 PM] Stopping server failed Error: Client is not running and can't be stopped. It's current state is: startFailed at GoLanguageClient.shutdown (/Users/hakim/projects/vscode-go/dist/goMain.js:21702:17) at GoLanguageClient.stop (/Users/hakim/projects/vscode-go/dist/goMain.js:21679:21) at GoLanguageClient.stop (/Users/hakim/projects/vscode-go/dist/goMain.js:23486:22) at GoLanguageClient.handleConnectionError (/Users/hakim/projects/vscode-go/dist/goMain.js:21920:16) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) [Error - 12:20:35 PM] [Error - 12:20:35 PM] gopls client: couldn't create connection to server. Message: Socket closed before the connection was established Code: -32099 Error starting language server: Error: Socket closed before the connection was established <-- this will be included in the initialization error field. `; const sanitizedTraceFromIssueVSCodeGo572LSP317 = `gopls client: couldn't create connection to server. Message: Socket closed before the connection was established Code: -32099 `; const trace2024MarchPanic = ` [Info - 9:58:40 AM] true [Error - 9:58:40 AM] gopls client: couldn't create connection to server. Message: Pending response rejected since connection got disposed Code: -32097 panic: crash goroutine 1 [running]: golang.org/x/tools/gopls/internal/cmd.(*Serve).Run(0xc000486310?, {0xc0000b8090?, 0x0?}, {0x0?, 0x0?, 0x0?}) /Users/Gopher/projects/tools/gopls/internal/cmd/serve.go:81 +0x25 golang.org/x/tools/internal/tool.Run({0x1012d048, 0xc00019c3f0}, 0xc000486310, {0x1012f9e0, 0xc000159b40}, {0xc0000b8090, 0x0, 0x0}) /Users/Gopher/projects/tools/internal/tool/tool.go:192 +0x691 golang.org/x/tools/gopls/internal/cmd.(*Application).Run(0xc000159b00, {0x1012d010, 0x107d9840}, {0xc0000b8090, 0x0, 0x0}) /Users/Gopher/projects/tools/gopls/internal/cmd/cmd.go:240 +0x147 golang.org/x/tools/internal/tool.Run({0x1012d010, 0x107d9840}, 0xc0004862a0, {0x1012f3a0, 0xc000159b00}, {0xc0000b8060, 0x4, 0x4}) /Users/Gopher/projects/tools/internal/tool/tool.go:192 +0x691 golang.org/x/tools/internal/tool.Main({0x1012d010, 0x107d9840}, {0x1012f3a0, 0xc000159b00}, {0xc0000b8060, 0x4, 0x4}) /Users/Gopher/projects/tools/internal/tool/tool.go:93 +0x12a main.main() /Users/Gopher/projects/tools/gopls/main.go:34 +0x109 [Error - 9:58:49 AM] [Error - 9:58:49 AM] gopls client: couldn't create connection to server. Message: Pending response rejected since connection got disposed Code: -32097 Error starting language server: Error: Pending response rejected since connection got disposed`; const sanitizedTrace2024MarchPanic = `panic: crash goroutine 1 [running]: golang.org/x/tools/gopls/internal/cmd.(*Serve).Run(0xc000486310?, {0xc0000b8090?, 0x0?}, {0x0?, 0x0?, 0x0?}) serve.go:81 +0x25 golang.org/x/tools/internal/tool.Run({0x1012d048, 0xc00019c3f0}, 0xc000486310, {0x1012f9e0, 0xc000159b40}, {0xc0000b8090, 0x0, 0x0}) tool.go:192 +0x691 golang.org/x/tools/gopls/internal/cmd.(*Application).Run(0xc000159b00, {0x1012d010, 0x107d9840}, {0xc0000b8090, 0x0, 0x0}) cmd.go:240 +0x147 golang.org/x/tools/internal/tool.Run({0x1012d010, 0x107d9840}, 0xc0004862a0, {0x1012f3a0, 0xc000159b00}, {0xc0000b8060, 0x4, 0x4}) tool.go:192 +0x691 golang.org/x/tools/internal/tool.Main({0x1012d010, 0x107d9840}, {0x1012f3a0, 0xc000159b00}, {0xc0000b8060, 0x4, 0x4}) tool.go:93 +0x12a main.main() main.go:34 +0x109 `;
vscode-go/extension/test/gopls/report.test.ts/0
{ "file_path": "vscode-go/extension/test/gopls/report.test.ts", "repo_id": "vscode-go", "token_count": 8144 }
790
/*--------------------------------------------------------- * Copyright 2021 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 { AttachItem, compareByProcessId, mergeExecutableAttachItem, parseGoVersionOutput } from '../../src/pickProcess'; import { parseLsofProcesses } from '../../src/utils/lsofProcessParser'; suite('Pick Process Tests', () => { test('Parse go version output', () => { const tt = [ { input: '/path/to/process/a: go1.16.2\n/path/to/process/b: go1.15.4\n/path/to/process/a b c: go1.8.0\n/path/to/process/d: go1.14', want: ['/path/to/process/a', '/path/to/process/b', '/path/to/process/a b c', '/path/to/process/d'] }, { input: 'C:\\path\\to\\process\\a: go1.16.2\nC:\\path\\to\\process\\b: go1.15.4\nC:\\path\\to\\process\\a b c: go1.8.0\nC:\\path\\to\\process\\d: go1.14', want: [ 'C:\\path\\to\\process\\a', 'C:\\path\\to\\process\\b', 'C:\\path\\to\\process\\a b c', 'C:\\path\\to\\process\\d' ] }, { input: 'go version go1.15.7 darwin/amd64', want: [] }, { input: '/path/to/process/a: go11a62b12\n/path/to/process/b: go1/15/4\n/path/to/process/a b c: gob.v.b\n/path/to/process/d: gp1.14', want: [] } ]; for (const tc of tt) { const got = parseGoVersionOutput(tc.input); assert.strictEqual(got.length, tc.want.length); for (let i = 0; i < got.length; i++) { assert.strictEqual(got[i], tc.want[i]); } } }); test('Parse lsof output', () => { const tt = [ { input: `p1010 ftxt n/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Renderer).app/Contents/MacOS/Code Helper (Renderer) ftxt n/Applications/Visual Studio Code.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Electron Framework ftxt n/Applications/Visual Studio Code.app/Contents/Frameworks/Electron Framework.framework/Versions/A/Libraries/libffmpeg.dylib p2020 ftxt n/User/name/go/bin/go`, want: [ { id: '1010', executable: '/Applications/Visual Studio Code.app/Contents/Frameworks/Code Helper (Renderer).app/Contents/MacOS/Code Helper (Renderer)' }, { id: '2020', executable: '/User/name/go/bin/go' } ] } ]; for (const tc of tt) { const got = parseLsofProcesses(tc.input); got.sort(compareByProcessId); assert.strictEqual(got.length, tc.want.length); for (let i = 0; i < got.length; i++) { assert.strictEqual(got[i].id, tc.want[i].id); assert.strictEqual(got[i].executable, tc.want[i].executable); } } }); test('Merge processes', () => { const tt: { processes: AttachItem[]; execInfo: AttachItem[]; want: AttachItem[]; }[] = [ { processes: [ { id: '100', processName: 'a', label: 'a' }, { id: '50', processName: 'b', label: 'b' }, { id: '130', processName: 'b', label: 'b' }, { id: '300', processName: 'c', label: 'c' } ], execInfo: [ { id: '50', label: '', executable: '/path/to/b' }, { id: '300', label: '', executable: '/path/to/c' } ], want: [ { id: '50', processName: 'b', label: 'b', executable: '/path/to/b' }, { id: '100', processName: 'a', label: 'a' }, { id: '130', processName: 'b', label: 'b' }, { id: '300', processName: 'c', label: 'c', executable: '/path/to/c' } ] } ]; for (const tc of tt) { mergeExecutableAttachItem(tc.processes, tc.execInfo); tc.processes.sort(compareByProcessId); assert.strictEqual(tc.processes.length, tc.want.length); for (let i = 0; i < tc.processes.length; i++) { assert.strictEqual(tc.processes[i].id, tc.want[i].id); assert.strictEqual(tc.processes[i].label, tc.want[i].label); assert.strictEqual(tc.processes[i].processName, tc.want[i].processName); assert.strictEqual(tc.processes[i].executable, tc.want[i].executable); } } }); });
vscode-go/extension/test/integration/pickProcess.test.ts/0
{ "file_path": "vscode-go/extension/test/integration/pickProcess.test.ts", "repo_id": "vscode-go", "token_count": 2071 }
791
// +build randomtag package main import "fmt" func main() { fmt.Prinln("hello") }
vscode-go/extension/test/testdata/buildTags/hello.go/0
{ "file_path": "vscode-go/extension/test/testdata/buildTags/hello.go", "repo_id": "vscode-go", "token_count": 35 }
792
package b import ( "fmt" "os" ) func main() { v := os.Env() fmt.Print(v) }
vscode-go/extension/test/testdata/coverage/b/b.go/0
{ "file_path": "vscode-go/extension/test/testdata/coverage/b/b.go", "repo_id": "vscode-go", "token_count": 46 }
793
package main import "testing" func TestB(t *testing.T) { t.Log("log") t.Error("error") }
vscode-go/extension/test/testdata/goTestTest/b/b_test.go/0
{ "file_path": "vscode-go/extension/test/testdata/goTestTest/b/b_test.go", "repo_id": "vscode-go", "token_count": 40 }
794
package linterTest import ( "errors" "fmt" ) func secondFunc() error { return errors.New(fmt.Sprint("Errors")) }
vscode-go/extension/test/testdata/linterTest/linter_2.go/0
{ "file_path": "vscode-go/extension/test/testdata/linterTest/linter_2.go", "repo_id": "vscode-go", "token_count": 49 }
795
package subTest import "testing" func TestMain(t *testing.T) { t.Log("Main") t.Run("Sub|Test", func(t *testing.T) { t.Log("Sub") }) t.Run("Sub|Test", func(t *testing.T) { t.Log("Sub#01") }) t.Run("Sub|Test#01", func(t *testing.T) { t.Log("Sub#01#01") }) t.Run("1 + 1", func(t *testing.T) { t.Run("Nested", func(t *testing.T) { t.Log("1 + 1 = 2") }) }) } func TestOther(t *testing.T) { t.Log("Other") }
vscode-go/extension/test/testdata/subTest/sub_test.go/0
{ "file_path": "vscode-go/extension/test/testdata/subTest/sub_test.go", "repo_id": "vscode-go", "token_count": 194 }
796
/* eslint-disable quotes */ /*--------------------------------------------------------- * Copyright 2023 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 { parseArgsString } from '../../src/utils/argsUtil'; suite('util tests', () => { test('parseArgsString Tests', () => { const tt = [ { test: 'Normal', args: ['value1 value2', ' value1 value2 ', ' value1 value2 '], want: ['value1', 'value2'] }, { test: 'Quoted', args: [`'value 1' "value 2" "value3" 'value4'`], want: ['value 1', 'value 2', 'value3', 'value4'] }, { test: 'SingleSurroundingDoubleQuotes', args: [`' "text" '`], want: [' "text" '] }, { test: 'DoubleSurroundingSingleQuotes', args: [`" 'text' "`], want: [` 'text' `] }, { test: 'EscapedQuotes', args: [`\\'a \\'b \\"c \\"d`], want: [`'a`, `'b`, '"c', '"d'] }, { test: 'EscapedQuotesInsideQuotes', args: [`'a\\' b\\"' "\\'c \\"d"`], want: [`a' b"`, `'c "d`] }, { test: 'Null', args: [`''`, '""'], want: [''] }, { test: 'Empty', args: ['', ' ', ' '], want: [] as string[] }, { test: 'NullAppendedToNull', args: [`''`, `''""`, '""""', `''''`], want: [''] }, { test: 'NullAppendedToNonNull', args: [`-e'' word""`, `''-e ""word`, `''-e'' ""word""`, `''""-e ""''word`], want: ['-e', 'word'] }, { test: 'UnmatchedSingleQuotes', args: [`something '`, `' something`], want: `args has unmatched single quotes (')` }, { test: 'UnmatchedDoubleQuotes', args: ['something "', '" something'], want: 'args has unmatched double quotes (")' } ]; for (const tc of tt) { for (const arg of tc.args) { const got = parseArgsString(arg); if (typeof tc.want === 'string') { // error case if (typeof got !== 'string') { assert.fail(`${tc.test}: expected error, but got: ` + JSON.stringify(got)); } const errorMatched = got.includes(tc.want); if (!errorMatched) { assert.fail( `${tc.test}: unmatched error, got: ${JSON.stringify( got )}, want error message include: ${JSON.stringify(tc.want)}` ); } } else { assert.deepStrictEqual( got, tc.want, `${tc.test}: parseArgsString(${JSON.stringify(arg)}), got: ${JSON.stringify( got )}, want: ${JSON.stringify(tc.want)}` ); } } } }); });
vscode-go/extension/test/unit/util.test.ts/0
{ "file_path": "vscode-go/extension/test/unit/util.test.ts", "repo_id": "vscode-go", "token_count": 1216 }
797
// 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. // This script is used to build and publish VS Code Go extension. // The script should be run from the root of the repository where package.json is located. // // The script requires the following environment variables to be set: // // TAG_NAME: the name of the tag to be released. // COMMIT_SHA: the commit SHA to be released (optional. if not set, it will be retrieved from git) // VSCE_PAT: the Personal Access Token for the VS Code Marketplace. // GITHUB_TOKEN: the GitHub token for the Go repository. // // This script requires the following tools to be installed: // // jq, npx, gh, git // // Usage: // // // package the extension (based on TAG_NAME). // go run build/release.go package // // publish the extension. // go run build/release.go publish package main import ( "bytes" "flag" "fmt" "os" "os/exec" "path/filepath" "regexp" "strings" ) var flagN = flag.Bool("n", false, "print the underlying commands but do not run them") func main() { flag.Parse() if flag.NArg() != 1 { usage() os.Exit(1) } cmd := flag.Arg(0) checkWD() requireTools("jq", "npx", "gh", "git") requireEnvVars("TAG_NAME") tagName, version, isRC := releaseVersionInfo() vsix := fmt.Sprintf("go-%s.vsix", version) switch cmd { case "package": buildPackage(version, tagName, vsix) case "publish": requireEnvVars("VSCE_PAT", "GITHUB_TOKEN") publish(tagName, vsix, isRC) default: usage() os.Exit(1) } } func usage() { fmt.Fprintf(os.Stderr, "Usage: %s <flags> [package|publish]\n\n", os.Args[0]) fmt.Fprintln(os.Stderr, "Flags:") flag.PrintDefaults() } func fatalf(format string, args ...any) { fmt.Fprintf(os.Stderr, format, args...) fmt.Fprintf(os.Stderr, "\n") os.Exit(1) } func requireTools(tools ...string) { for _, tool := range tools { if _, err := exec.LookPath(tool); err != nil { fatalf("required tool %q not found", tool) } } } func requireEnvVars(vars ...string) { for _, v := range vars { if os.Getenv(v) == "" { fatalf("required environment variable %q not set", v) } } } // checkWD checks if the working directory is the extension directory where package.json is located. func checkWD() { wd, err := os.Getwd() if err != nil { fatalf("failed to get working directory") } // check if package.json is in the working directory if _, err := os.Stat("package.json"); os.IsNotExist(err) { fatalf("package.json not found in working directory %q", wd) } } // releaseVersionInfo computes the version and label information for this release. // It requires the TAG_NAME environment variable to be set and the tag matches the version info embedded in package.json. func releaseVersionInfo() (tagName, version string, isPrerelease bool) { tagName = os.Getenv("TAG_NAME") if tagName == "" { fatalf("TAG_NAME environment variable is not set") } // versionTag should be of the form vMajor.Minor.Patch[-rc.N]. // e.g. v1.1.0-rc.1, v1.1.0 // The MajorMinorPatch part should match the version in package.json. // The optional `-rc.N` part is captured as the `Label` group // and the validity is checked below. versionTagRE := regexp.MustCompile(`^v(?P<MajorMinorPatch>\d+\.\d+\.\d+)(?P<Label>\S*)$`) m := versionTagRE.FindStringSubmatch(tagName) if m == nil { fatalf("TAG_NAME environment variable %q is not a valid version", tagName) } mmp := m[versionTagRE.SubexpIndex("MajorMinorPatch")] label := m[versionTagRE.SubexpIndex("Label")] if label != "" { if !strings.HasPrefix(label, "-rc.") { fatalf("TAG_NAME environment variable %q is not a valid release candidate version", tagName) } isPrerelease = true } cmd := exec.Command("jq", "-r", ".version", "package.json") cmd.Stderr = os.Stderr var buf bytes.Buffer cmd.Stdout = &buf if err := commandRun(cmd); err != nil { fatalf("failed to read package.json version") } versionInPackageJSON := buf.Bytes() if *flagN { return tagName, mmp + label, isPrerelease } if got := string(bytes.TrimSpace(versionInPackageJSON)); got != mmp { fatalf("package.json version %q does not match TAG_NAME %q", got, tagName) } return tagName, mmp + label, isPrerelease } func commandRun(cmd *exec.Cmd) error { if *flagN { if cmd.Dir != "" { fmt.Fprintf(os.Stderr, "cd %v\n", cmd.Dir) } fmt.Fprintf(os.Stderr, "%v\n", strings.Join(cmd.Args, " ")) return nil } return cmd.Run() } func copy(dst, src string) error { if *flagN { fmt.Fprintf(os.Stderr, "cp %s %s\n", src, dst) return nil } data, err := os.ReadFile(src) if err != nil { return err } return os.WriteFile(dst, data, 0644) } // buildPackage builds the extension of the given version, using npx vsce package. func buildPackage(version, tagName, output string) { if err := copy("README.md", filepath.Join("..", "README.md")); err != nil { fatalf("failed to copy README.md: %v", err) } // build the package. cmd := exec.Command("npx", "vsce", "package", "-o", output, "--baseContentUrl", "https://github.com/golang/vscode-go/raw/"+tagName, "--baseImagesUrl", "https://github.com/golang/vscode-go/raw/"+tagName, "--no-update-package-json", "--no-git-tag-version", version) cmd.Stderr = os.Stderr if err := commandRun(cmd); err != nil { fatalf("failed to build package: %v", err) } } // publish publishes the extension to the VS Code Marketplace and GitHub, using npx vsce and gh release create. func publish(tagName, packageFile string, isPrerelease bool) { // check if the package file exists. if *flagN { fmt.Fprintf(os.Stderr, "stat %s\n", packageFile) } else { if _, err := os.Stat(packageFile); os.IsNotExist(err) { fatalf("package file %q does not exist. Did you run 'go run build/release.go package'?", packageFile) } } // publish release to GitHub. This will create a draft release - manually publish it after reviewing the draft. // TODO(hyangah): populate the changelog (the first section of CHANGELOG.md) and pass it using --notes-file instead of --generate-notes. ghArgs := []string{"release", "create", "--generate-notes", "--target", commitSHA(), "--title", "Release " + tagName, "--draft"} fmt.Printf("%s\n", strings.Join(ghArgs, " ")) if isPrerelease { ghArgs = append(ghArgs, "--prerelease") } ghArgs = append(ghArgs, "-R", "github.com/golang/vscode-go") ghArgs = append(ghArgs, tagName, packageFile) cmd := exec.Command("gh", ghArgs...) cmd.Stderr = os.Stderr if err := commandRun(cmd); err != nil { fatalf("failed to publish release: %v", err) } if isPrerelease { return // TODO: release with the -pre-release flag if isPrerelease is set. } npxVsceArgs := []string{"vsce", "publish", "-i", packageFile} cmd2 := exec.Command("npx", npxVsceArgs...) cmd2.Stderr = os.Stderr if err := commandRun(cmd2); err != nil { fatalf("failed to publish release") } } // commitSHA returns COMMIT_SHA environment variable, or the commit SHA of the current branch. func commitSHA() string { if commitSHA := os.Getenv("COMMIT_SHA"); commitSHA != "" { return commitSHA } cmd := exec.Command("git", "rev-parse", "HEAD") cmd.Stderr = os.Stderr commitSHA, err := cmd.Output() if err != nil { fatalf("failed to get commit SHA") } return strings.TrimSpace(string(commitSHA)) }
vscode-go/extension/tools/release/release.go/0
{ "file_path": "vscode-go/extension/tools/release/release.go", "repo_id": "vscode-go", "token_count": 2661 }
798
// 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 provides automatic access to certificates from Let's Encrypt // and any other ACME-based CA. // // This package is a work in progress and makes no API stability promises. package autocert import ( "bytes" "context" "crypto" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/pem" "errors" "fmt" "io" mathrand "math/rand" "net" "net/http" "path" "strings" "sync" "time" "golang.org/x/crypto/acme" "golang.org/x/net/idna" ) // DefaultACMEDirectory is the default ACME Directory URL used when the Manager's Client is nil. const DefaultACMEDirectory = "https://acme-v02.api.letsencrypt.org/directory" // createCertRetryAfter is how much time to wait before removing a failed state // entry due to an unsuccessful createCert call. // This is a variable instead of a const for testing. // TODO: Consider making it configurable or an exp backoff? var createCertRetryAfter = time.Minute // pseudoRand is safe for concurrent use. var pseudoRand *lockedMathRand var errPreRFC = errors.New("autocert: ACME server doesn't support RFC 8555") func init() { src := mathrand.NewSource(time.Now().UnixNano()) pseudoRand = &lockedMathRand{rnd: mathrand.New(src)} } // AcceptTOS is a Manager.Prompt function that always returns true to // indicate acceptance of the CA's Terms of Service during account // registration. func AcceptTOS(tosURL string) bool { return true } // HostPolicy specifies which host names the Manager is allowed to respond to. // It returns a non-nil error if the host should be rejected. // The returned error is accessible via tls.Conn.Handshake and its callers. // See Manager's HostPolicy field and GetCertificate method docs for more details. type HostPolicy func(ctx context.Context, host string) error // HostWhitelist returns a policy where only the specified host names are allowed. // Only exact matches are currently supported. Subdomains, regexp or wildcard // will not match. // // Note that all hosts will be converted to Punycode via idna.Lookup.ToASCII so that // Manager.GetCertificate can handle the Unicode IDN and mixedcase hosts correctly. // Invalid hosts will be silently ignored. func HostWhitelist(hosts ...string) HostPolicy { whitelist := make(map[string]bool, len(hosts)) for _, h := range hosts { if h, err := idna.Lookup.ToASCII(h); err == nil { whitelist[h] = true } } return func(_ context.Context, host string) error { if !whitelist[host] { return fmt.Errorf("acme/autocert: host %q not configured in HostWhitelist", host) } return nil } } // defaultHostPolicy is used when Manager.HostPolicy is not set. func defaultHostPolicy(context.Context, string) error { return nil } // Manager is a stateful certificate manager built on top of acme.Client. // It obtains and refreshes certificates automatically using "tls-alpn-01" // or "http-01" challenge types, as well as providing them to a TLS server // via tls.Config. // // You must specify a cache implementation, such as DirCache, // to reuse obtained certificates across program restarts. // Otherwise your server is very likely to exceed the certificate // issuer's request rate limits. type Manager struct { // Prompt specifies a callback function to conditionally accept a CA's Terms of Service (TOS). // The registration may require the caller to agree to the CA's TOS. // If so, Manager calls Prompt with a TOS URL provided by the CA. Prompt should report // whether the caller agrees to the terms. // // To always accept the terms, the callers can use AcceptTOS. Prompt func(tosURL string) bool // Cache optionally stores and retrieves previously-obtained certificates // and other state. If nil, certs will only be cached for the lifetime of // the Manager. Multiple Managers can share the same Cache. // // Using a persistent Cache, such as DirCache, is strongly recommended. Cache Cache // HostPolicy controls which domains the Manager will attempt // to retrieve new certificates for. It does not affect cached certs. // // If non-nil, HostPolicy is called before requesting a new cert. // If nil, all hosts are currently allowed. This is not recommended, // as it opens a potential attack where clients connect to a server // by IP address and pretend to be asking for an incorrect host name. // Manager will attempt to obtain a certificate for that host, incorrectly, // eventually reaching the CA's rate limit for certificate requests // and making it impossible to obtain actual certificates. // // See GetCertificate for more details. HostPolicy HostPolicy // RenewBefore optionally specifies how early certificates should // be renewed before they expire. // // If zero, they're renewed 30 days before expiration. RenewBefore time.Duration // Client is used to perform low-level operations, such as account registration // and requesting new certificates. // // If Client is nil, a zero-value acme.Client is used with DefaultACMEDirectory // as the directory endpoint. // If the Client.Key is nil, a new ECDSA P-256 key is generated and, // if Cache is not nil, stored in cache. // // Mutating the field after the first call of GetCertificate method will have no effect. Client *acme.Client // Email optionally specifies a contact email address. // This is used by CAs, such as Let's Encrypt, to notify about problems // with issued certificates. // // If the Client's account key is already registered, Email is not used. Email string // ForceRSA used to make the Manager generate RSA certificates. It is now ignored. // // Deprecated: the Manager will request the correct type of certificate based // on what each client supports. ForceRSA bool // ExtraExtensions are used when generating a new CSR (Certificate Request), // thus allowing customization of the resulting certificate. // For instance, TLS Feature Extension (RFC 7633) can be used // to prevent an OCSP downgrade attack. // // The field value is passed to crypto/x509.CreateCertificateRequest // in the template's ExtraExtensions field as is. ExtraExtensions []pkix.Extension // ExternalAccountBinding optionally represents an arbitrary binding to an // account of the CA to which the ACME server is tied. // See RFC 8555, Section 7.3.4 for more details. ExternalAccountBinding *acme.ExternalAccountBinding clientMu sync.Mutex client *acme.Client // initialized by acmeClient method stateMu sync.Mutex state map[certKey]*certState // renewal tracks the set of domains currently running renewal timers. renewalMu sync.Mutex renewal map[certKey]*domainRenewal // challengeMu guards tryHTTP01, certTokens and httpTokens. challengeMu sync.RWMutex // tryHTTP01 indicates whether the Manager should try "http-01" challenge type // during the authorization flow. tryHTTP01 bool // httpTokens contains response body values for http-01 challenges // and is keyed by the URL path at which a challenge response is expected // to be provisioned. // The entries are stored for the duration of the authorization flow. httpTokens map[string][]byte // certTokens contains temporary certificates for tls-alpn-01 challenges // and is keyed by the domain name which matches the ClientHello server name. // The entries are stored for the duration of the authorization flow. certTokens map[string]*tls.Certificate // nowFunc, if not nil, returns the current time. This may be set for // testing purposes. nowFunc func() time.Time } // certKey is the key by which certificates are tracked in state, renewal and cache. type certKey struct { domain string // without trailing dot isRSA bool // RSA cert for legacy clients (as opposed to default ECDSA) isToken bool // tls-based challenge token cert; key type is undefined regardless of isRSA } func (c certKey) String() string { if c.isToken { return c.domain + "+token" } if c.isRSA { return c.domain + "+rsa" } return c.domain } // TLSConfig creates a new TLS config suitable for net/http.Server servers, // supporting HTTP/2 and the tls-alpn-01 ACME challenge type. func (m *Manager) TLSConfig() *tls.Config { return &tls.Config{ GetCertificate: m.GetCertificate, NextProtos: []string{ "h2", "http/1.1", // enable HTTP/2 acme.ALPNProto, // enable tls-alpn ACME challenges }, } } // GetCertificate implements the tls.Config.GetCertificate hook. // It provides a TLS certificate for hello.ServerName host, including answering // tls-alpn-01 challenges. // All other fields of hello are ignored. // // If m.HostPolicy is non-nil, GetCertificate calls the policy before requesting // a new cert. A non-nil error returned from m.HostPolicy halts TLS negotiation. // The error is propagated back to the caller of GetCertificate and is user-visible. // This does not affect cached certs. See HostPolicy field description for more details. // // If GetCertificate is used directly, instead of via Manager.TLSConfig, package users will // also have to add acme.ALPNProto to NextProtos for tls-alpn-01, or use HTTPHandler for http-01. func (m *Manager) GetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) { if m.Prompt == nil { return nil, errors.New("acme/autocert: Manager.Prompt not set") } name := hello.ServerName if name == "" { return nil, errors.New("acme/autocert: missing server name") } if !strings.Contains(strings.Trim(name, "."), ".") { return nil, errors.New("acme/autocert: server name component count invalid") } // Note that this conversion is necessary because some server names in the handshakes // started by some clients (such as cURL) are not converted to Punycode, which will // prevent us from obtaining certificates for them. In addition, we should also treat // example.com and EXAMPLE.COM as equivalent and return the same certificate for them. // Fortunately, this conversion also helped us deal with this kind of mixedcase problems. // // Due to the "σςΣ" problem (see https://unicode.org/faq/idn.html#22), we can't use // idna.Punycode.ToASCII (or just idna.ToASCII) here. name, err := idna.Lookup.ToASCII(name) if err != nil { return nil, errors.New("acme/autocert: server name contains invalid character") } // In the worst-case scenario, the timeout needs to account for caching, host policy, // domain ownership verification and certificate issuance. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() // Check whether this is a token cert requested for TLS-ALPN challenge. if wantsTokenCert(hello) { m.challengeMu.RLock() defer m.challengeMu.RUnlock() if cert := m.certTokens[name]; cert != nil { return cert, nil } if cert, err := m.cacheGet(ctx, certKey{domain: name, isToken: true}); err == nil { return cert, nil } // TODO: cache error results? return nil, fmt.Errorf("acme/autocert: no token cert for %q", name) } // regular domain ck := certKey{ domain: strings.TrimSuffix(name, "."), // golang.org/issue/18114 isRSA: !supportsECDSA(hello), } cert, err := m.cert(ctx, ck) if err == nil { return cert, nil } if err != ErrCacheMiss { return nil, err } // first-time if err := m.hostPolicy()(ctx, name); err != nil { return nil, err } cert, err = m.createCert(ctx, ck) if err != nil { return nil, err } m.cachePut(ctx, ck, cert) return cert, nil } // wantsTokenCert reports whether a TLS request with SNI is made by a CA server // for a challenge verification. func wantsTokenCert(hello *tls.ClientHelloInfo) bool { // tls-alpn-01 if len(hello.SupportedProtos) == 1 && hello.SupportedProtos[0] == acme.ALPNProto { return true } return false } func supportsECDSA(hello *tls.ClientHelloInfo) bool { // The "signature_algorithms" extension, if present, limits the key exchange // algorithms allowed by the cipher suites. See RFC 5246, section 7.4.1.4.1. if hello.SignatureSchemes != nil { ecdsaOK := false schemeLoop: for _, scheme := range hello.SignatureSchemes { const tlsECDSAWithSHA1 tls.SignatureScheme = 0x0203 // constant added in Go 1.10 switch scheme { case tlsECDSAWithSHA1, tls.ECDSAWithP256AndSHA256, tls.ECDSAWithP384AndSHA384, tls.ECDSAWithP521AndSHA512: ecdsaOK = true break schemeLoop } } if !ecdsaOK { return false } } if hello.SupportedCurves != nil { ecdsaOK := false for _, curve := range hello.SupportedCurves { if curve == tls.CurveP256 { ecdsaOK = true break } } if !ecdsaOK { return false } } for _, suite := range hello.CipherSuites { switch suite { case tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: return true } } return false } // HTTPHandler configures the Manager to provision ACME "http-01" challenge responses. // It returns an http.Handler that responds to the challenges and must be // running on port 80. If it receives a request that is not an ACME challenge, // it delegates the request to the optional fallback handler. // // If fallback is nil, the returned handler redirects all GET and HEAD requests // to the default TLS port 443 with 302 Found status code, preserving the original // request path and query. It responds with 400 Bad Request to all other HTTP methods. // The fallback is not protected by the optional HostPolicy. // // Because the fallback handler is run with unencrypted port 80 requests, // the fallback should not serve TLS-only requests. // // If HTTPHandler is never called, the Manager will only use the "tls-alpn-01" // challenge for domain verification. func (m *Manager) HTTPHandler(fallback http.Handler) http.Handler { m.challengeMu.Lock() defer m.challengeMu.Unlock() m.tryHTTP01 = true if fallback == nil { fallback = http.HandlerFunc(handleHTTPRedirect) } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !strings.HasPrefix(r.URL.Path, "/.well-known/acme-challenge/") { fallback.ServeHTTP(w, r) return } // A reasonable context timeout for cache and host policy only, // because we don't wait for a new certificate issuance here. ctx, cancel := context.WithTimeout(r.Context(), time.Minute) defer cancel() if err := m.hostPolicy()(ctx, r.Host); err != nil { http.Error(w, err.Error(), http.StatusForbidden) return } data, err := m.httpToken(ctx, r.URL.Path) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.Write(data) }) } func handleHTTPRedirect(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" && r.Method != "HEAD" { http.Error(w, "Use HTTPS", http.StatusBadRequest) return } target := "https://" + stripPort(r.Host) + r.URL.RequestURI() http.Redirect(w, r, target, http.StatusFound) } func stripPort(hostport string) string { host, _, err := net.SplitHostPort(hostport) if err != nil { return hostport } return net.JoinHostPort(host, "443") } // cert returns an existing certificate either from m.state or cache. // If a certificate is found in cache but not in m.state, the latter will be filled // with the cached value. func (m *Manager) cert(ctx context.Context, ck certKey) (*tls.Certificate, error) { m.stateMu.Lock() if s, ok := m.state[ck]; ok { m.stateMu.Unlock() s.RLock() defer s.RUnlock() return s.tlscert() } defer m.stateMu.Unlock() cert, err := m.cacheGet(ctx, ck) if err != nil { return nil, err } signer, ok := cert.PrivateKey.(crypto.Signer) if !ok { return nil, errors.New("acme/autocert: private key cannot sign") } if m.state == nil { m.state = make(map[certKey]*certState) } s := &certState{ key: signer, cert: cert.Certificate, leaf: cert.Leaf, } m.state[ck] = s m.startRenew(ck, s.key, s.leaf.NotAfter) return cert, nil } // cacheGet always returns a valid certificate, or an error otherwise. // If a cached certificate exists but is not valid, ErrCacheMiss is returned. func (m *Manager) cacheGet(ctx context.Context, ck certKey) (*tls.Certificate, error) { if m.Cache == nil { return nil, ErrCacheMiss } data, err := m.Cache.Get(ctx, ck.String()) if err != nil { return nil, err } // private priv, pub := pem.Decode(data) if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { return nil, ErrCacheMiss } privKey, err := parsePrivateKey(priv.Bytes) if err != nil { return nil, err } // public var pubDER [][]byte for len(pub) > 0 { var b *pem.Block b, pub = pem.Decode(pub) if b == nil { break } pubDER = append(pubDER, b.Bytes) } if len(pub) > 0 { // Leftover content not consumed by pem.Decode. Corrupt. Ignore. return nil, ErrCacheMiss } // verify and create TLS cert leaf, err := validCert(ck, pubDER, privKey, m.now()) if err != nil { return nil, ErrCacheMiss } tlscert := &tls.Certificate{ Certificate: pubDER, PrivateKey: privKey, Leaf: leaf, } return tlscert, nil } func (m *Manager) cachePut(ctx context.Context, ck certKey, tlscert *tls.Certificate) error { if m.Cache == nil { return nil } // contains PEM-encoded data var buf bytes.Buffer // private switch key := tlscert.PrivateKey.(type) { case *ecdsa.PrivateKey: if err := encodeECDSAKey(&buf, key); err != nil { return err } case *rsa.PrivateKey: b := x509.MarshalPKCS1PrivateKey(key) pb := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: b} if err := pem.Encode(&buf, pb); err != nil { return err } default: return errors.New("acme/autocert: unknown private key type") } // public for _, b := range tlscert.Certificate { pb := &pem.Block{Type: "CERTIFICATE", Bytes: b} if err := pem.Encode(&buf, pb); err != nil { return err } } return m.Cache.Put(ctx, ck.String(), buf.Bytes()) } func encodeECDSAKey(w io.Writer, key *ecdsa.PrivateKey) error { b, err := x509.MarshalECPrivateKey(key) if err != nil { return err } pb := &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} return pem.Encode(w, pb) } // createCert starts the domain ownership verification and returns a certificate // for that domain upon success. // // If the domain is already being verified, it waits for the existing verification to complete. // Either way, createCert blocks for the duration of the whole process. func (m *Manager) createCert(ctx context.Context, ck certKey) (*tls.Certificate, error) { // TODO: maybe rewrite this whole piece using sync.Once state, err := m.certState(ck) if err != nil { return nil, err } // state may exist if another goroutine is already working on it // in which case just wait for it to finish if !state.locked { state.RLock() defer state.RUnlock() return state.tlscert() } // We are the first; state is locked. // Unblock the readers when domain ownership is verified // and we got the cert or the process failed. defer state.Unlock() state.locked = false der, leaf, err := m.authorizedCert(ctx, state.key, ck) if err != nil { // Remove the failed state after some time, // making the manager call createCert again on the following TLS hello. didRemove := testDidRemoveState // The lifetime of this timer is untracked, so copy mutable local state to avoid races. time.AfterFunc(createCertRetryAfter, func() { defer didRemove(ck) m.stateMu.Lock() defer m.stateMu.Unlock() // Verify the state hasn't changed and it's still invalid // before deleting. s, ok := m.state[ck] if !ok { return } if _, err := validCert(ck, s.cert, s.key, m.now()); err == nil { return } delete(m.state, ck) }) return nil, err } state.cert = der state.leaf = leaf m.startRenew(ck, state.key, state.leaf.NotAfter) return state.tlscert() } // certState returns a new or existing certState. // If a new certState is returned, state.exist is false and the state is locked. // The returned error is non-nil only in the case where a new state could not be created. func (m *Manager) certState(ck certKey) (*certState, error) { m.stateMu.Lock() defer m.stateMu.Unlock() if m.state == nil { m.state = make(map[certKey]*certState) } // existing state if state, ok := m.state[ck]; ok { return state, nil } // new locked state var ( err error key crypto.Signer ) if ck.isRSA { key, err = rsa.GenerateKey(rand.Reader, 2048) } else { key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) } if err != nil { return nil, err } state := &certState{ key: key, locked: true, } state.Lock() // will be unlocked by m.certState caller m.state[ck] = state return state, nil } // authorizedCert starts the domain ownership verification process and requests a new cert upon success. // The key argument is the certificate private key. func (m *Manager) authorizedCert(ctx context.Context, key crypto.Signer, ck certKey) (der [][]byte, leaf *x509.Certificate, err error) { csr, err := certRequest(key, ck.domain, m.ExtraExtensions) if err != nil { return nil, nil, err } client, err := m.acmeClient(ctx) if err != nil { return nil, nil, err } dir, err := client.Discover(ctx) if err != nil { return nil, nil, err } if dir.OrderURL == "" { return nil, nil, errPreRFC } o, err := m.verifyRFC(ctx, client, ck.domain) if err != nil { return nil, nil, err } chain, _, err := client.CreateOrderCert(ctx, o.FinalizeURL, csr, true) if err != nil { return nil, nil, err } leaf, err = validCert(ck, chain, key, m.now()) if err != nil { return nil, nil, err } return chain, leaf, nil } // verifyRFC runs the identifier (domain) order-based authorization flow for RFC compliant CAs // using each applicable ACME challenge type. func (m *Manager) verifyRFC(ctx context.Context, client *acme.Client, domain string) (*acme.Order, error) { // Try each supported challenge type starting with a new order each time. // The nextTyp index of the next challenge type to try is shared across // all order authorizations: if we've tried a challenge type once and it didn't work, // it will most likely not work on another order's authorization either. challengeTypes := m.supportedChallengeTypes() nextTyp := 0 // challengeTypes index AuthorizeOrderLoop: for { o, err := client.AuthorizeOrder(ctx, acme.DomainIDs(domain)) if err != nil { return nil, err } // Remove all hanging authorizations to reduce rate limit quotas // after we're done. defer func(urls []string) { go m.deactivatePendingAuthz(urls) }(o.AuthzURLs) // Check if there's actually anything we need to do. switch o.Status { case acme.StatusReady: // Already authorized. return o, nil case acme.StatusPending: // Continue normal Order-based flow. default: return nil, fmt.Errorf("acme/autocert: invalid new order status %q; order URL: %q", o.Status, o.URI) } // Satisfy all pending authorizations. for _, zurl := range o.AuthzURLs { z, err := client.GetAuthorization(ctx, zurl) if err != nil { return nil, err } if z.Status != acme.StatusPending { // We are interested only in pending authorizations. continue } // Pick the next preferred challenge. var chal *acme.Challenge for chal == nil && nextTyp < len(challengeTypes) { chal = pickChallenge(challengeTypes[nextTyp], z.Challenges) nextTyp++ } if chal == nil { return nil, fmt.Errorf("acme/autocert: unable to satisfy %q for domain %q: no viable challenge type found", z.URI, domain) } // Respond to the challenge and wait for validation result. cleanup, err := m.fulfill(ctx, client, chal, domain) if err != nil { continue AuthorizeOrderLoop } defer cleanup() if _, err := client.Accept(ctx, chal); err != nil { continue AuthorizeOrderLoop } if _, err := client.WaitAuthorization(ctx, z.URI); err != nil { continue AuthorizeOrderLoop } } // All authorizations are satisfied. // Wait for the CA to update the order status. o, err = client.WaitOrder(ctx, o.URI) if err != nil { continue AuthorizeOrderLoop } return o, nil } } func pickChallenge(typ string, chal []*acme.Challenge) *acme.Challenge { for _, c := range chal { if c.Type == typ { return c } } return nil } func (m *Manager) supportedChallengeTypes() []string { m.challengeMu.RLock() defer m.challengeMu.RUnlock() typ := []string{"tls-alpn-01"} if m.tryHTTP01 { typ = append(typ, "http-01") } return typ } // deactivatePendingAuthz relinquishes all authorizations identified by the elements // of the provided uri slice which are in "pending" state. // It ignores revocation errors. // // deactivatePendingAuthz takes no context argument and instead runs with its own // "detached" context because deactivations are done in a goroutine separate from // that of the main issuance or renewal flow. func (m *Manager) deactivatePendingAuthz(uri []string) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() client, err := m.acmeClient(ctx) if err != nil { return } for _, u := range uri { z, err := client.GetAuthorization(ctx, u) if err == nil && z.Status == acme.StatusPending { client.RevokeAuthorization(ctx, u) } } } // fulfill provisions a response to the challenge chal. // The cleanup is non-nil only if provisioning succeeded. func (m *Manager) fulfill(ctx context.Context, client *acme.Client, chal *acme.Challenge, domain string) (cleanup func(), err error) { switch chal.Type { case "tls-alpn-01": cert, err := client.TLSALPN01ChallengeCert(chal.Token, domain) if err != nil { return nil, err } m.putCertToken(ctx, domain, &cert) return func() { go m.deleteCertToken(domain) }, nil case "http-01": resp, err := client.HTTP01ChallengeResponse(chal.Token) if err != nil { return nil, err } p := client.HTTP01ChallengePath(chal.Token) m.putHTTPToken(ctx, p, resp) return func() { go m.deleteHTTPToken(p) }, nil } return nil, fmt.Errorf("acme/autocert: unknown challenge type %q", chal.Type) } // putCertToken stores the token certificate with the specified name // in both m.certTokens map and m.Cache. func (m *Manager) putCertToken(ctx context.Context, name string, cert *tls.Certificate) { m.challengeMu.Lock() defer m.challengeMu.Unlock() if m.certTokens == nil { m.certTokens = make(map[string]*tls.Certificate) } m.certTokens[name] = cert m.cachePut(ctx, certKey{domain: name, isToken: true}, cert) } // deleteCertToken removes the token certificate with the specified name // from both m.certTokens map and m.Cache. func (m *Manager) deleteCertToken(name string) { m.challengeMu.Lock() defer m.challengeMu.Unlock() delete(m.certTokens, name) if m.Cache != nil { ck := certKey{domain: name, isToken: true} m.Cache.Delete(context.Background(), ck.String()) } } // httpToken retrieves an existing http-01 token value from an in-memory map // or the optional cache. func (m *Manager) httpToken(ctx context.Context, tokenPath string) ([]byte, error) { m.challengeMu.RLock() defer m.challengeMu.RUnlock() if v, ok := m.httpTokens[tokenPath]; ok { return v, nil } if m.Cache == nil { return nil, fmt.Errorf("acme/autocert: no token at %q", tokenPath) } return m.Cache.Get(ctx, httpTokenCacheKey(tokenPath)) } // putHTTPToken stores an http-01 token value using tokenPath as key // in both in-memory map and the optional Cache. // // It ignores any error returned from Cache.Put. func (m *Manager) putHTTPToken(ctx context.Context, tokenPath, val string) { m.challengeMu.Lock() defer m.challengeMu.Unlock() if m.httpTokens == nil { m.httpTokens = make(map[string][]byte) } b := []byte(val) m.httpTokens[tokenPath] = b if m.Cache != nil { m.Cache.Put(ctx, httpTokenCacheKey(tokenPath), b) } } // deleteHTTPToken removes an http-01 token value from both in-memory map // and the optional Cache, ignoring any error returned from the latter. // // If m.Cache is non-nil, it blocks until Cache.Delete returns without a timeout. func (m *Manager) deleteHTTPToken(tokenPath string) { m.challengeMu.Lock() defer m.challengeMu.Unlock() delete(m.httpTokens, tokenPath) if m.Cache != nil { m.Cache.Delete(context.Background(), httpTokenCacheKey(tokenPath)) } } // httpTokenCacheKey returns a key at which an http-01 token value may be stored // in the Manager's optional Cache. func httpTokenCacheKey(tokenPath string) string { return path.Base(tokenPath) + "+http-01" } // startRenew starts a cert renewal timer loop, one per domain. // // The loop is scheduled in two cases: // - a cert was fetched from cache for the first time (wasn't in m.state) // - a new cert was created by m.createCert // // The key argument is a certificate private key. // The exp argument is the cert expiration time (NotAfter). func (m *Manager) startRenew(ck certKey, key crypto.Signer, exp time.Time) { m.renewalMu.Lock() defer m.renewalMu.Unlock() if m.renewal[ck] != nil { // another goroutine is already on it return } if m.renewal == nil { m.renewal = make(map[certKey]*domainRenewal) } dr := &domainRenewal{m: m, ck: ck, key: key} m.renewal[ck] = dr dr.start(exp) } // stopRenew stops all currently running cert renewal timers. // The timers are not restarted during the lifetime of the Manager. func (m *Manager) stopRenew() { m.renewalMu.Lock() defer m.renewalMu.Unlock() for name, dr := range m.renewal { delete(m.renewal, name) dr.stop() } } func (m *Manager) accountKey(ctx context.Context) (crypto.Signer, error) { const keyName = "acme_account+key" // Previous versions of autocert stored the value under a different key. const legacyKeyName = "acme_account.key" genKey := func() (*ecdsa.PrivateKey, error) { return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) } if m.Cache == nil { return genKey() } data, err := m.Cache.Get(ctx, keyName) if err == ErrCacheMiss { data, err = m.Cache.Get(ctx, legacyKeyName) } if err == ErrCacheMiss { key, err := genKey() if err != nil { return nil, err } var buf bytes.Buffer if err := encodeECDSAKey(&buf, key); err != nil { return nil, err } if err := m.Cache.Put(ctx, keyName, buf.Bytes()); err != nil { return nil, err } return key, nil } if err != nil { return nil, err } priv, _ := pem.Decode(data) if priv == nil || !strings.Contains(priv.Type, "PRIVATE") { return nil, errors.New("acme/autocert: invalid account key found in cache") } return parsePrivateKey(priv.Bytes) } func (m *Manager) acmeClient(ctx context.Context) (*acme.Client, error) { m.clientMu.Lock() defer m.clientMu.Unlock() if m.client != nil { return m.client, nil } client := m.Client if client == nil { client = &acme.Client{DirectoryURL: DefaultACMEDirectory} } if client.Key == nil { var err error client.Key, err = m.accountKey(ctx) if err != nil { return nil, err } } if client.UserAgent == "" { client.UserAgent = "autocert" } var contact []string if m.Email != "" { contact = []string{"mailto:" + m.Email} } a := &acme.Account{Contact: contact, ExternalAccountBinding: m.ExternalAccountBinding} _, err := client.Register(ctx, a, m.Prompt) if err == nil || isAccountAlreadyExist(err) { m.client = client err = nil } return m.client, err } // isAccountAlreadyExist reports whether the err, as returned from acme.Client.Register, // indicates the account has already been registered. func isAccountAlreadyExist(err error) bool { if err == acme.ErrAccountAlreadyExists { return true } ae, ok := err.(*acme.Error) return ok && ae.StatusCode == http.StatusConflict } func (m *Manager) hostPolicy() HostPolicy { if m.HostPolicy != nil { return m.HostPolicy } return defaultHostPolicy } func (m *Manager) renewBefore() time.Duration { if m.RenewBefore > renewJitter { return m.RenewBefore } return 720 * time.Hour // 30 days } func (m *Manager) now() time.Time { if m.nowFunc != nil { return m.nowFunc() } return time.Now() } // certState is ready when its mutex is unlocked for reading. type certState struct { sync.RWMutex locked bool // locked for read/write key crypto.Signer // private key for cert cert [][]byte // DER encoding leaf *x509.Certificate // parsed cert[0]; always non-nil if cert != nil } // tlscert creates a tls.Certificate from s.key and s.cert. // Callers should wrap it in s.RLock() and s.RUnlock(). func (s *certState) tlscert() (*tls.Certificate, error) { if s.key == nil { return nil, errors.New("acme/autocert: missing signer") } if len(s.cert) == 0 { return nil, errors.New("acme/autocert: missing certificate") } return &tls.Certificate{ PrivateKey: s.key, Certificate: s.cert, Leaf: s.leaf, }, nil } // certRequest generates a CSR for the given common name. func certRequest(key crypto.Signer, name string, ext []pkix.Extension) ([]byte, error) { req := &x509.CertificateRequest{ Subject: pkix.Name{CommonName: name}, DNSNames: []string{name}, ExtraExtensions: ext, } return x509.CreateCertificateRequest(rand.Reader, req, key) } // Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates // PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. // OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. // // Inspired by parsePrivateKey in crypto/tls/tls.go. func parsePrivateKey(der []byte) (crypto.Signer, error) { if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { return key, nil } if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { switch key := key.(type) { case *rsa.PrivateKey: return key, nil case *ecdsa.PrivateKey: return key, nil default: return nil, errors.New("acme/autocert: unknown private key type in PKCS#8 wrapping") } } if key, err := x509.ParseECPrivateKey(der); err == nil { return key, nil } return nil, errors.New("acme/autocert: failed to parse private key") } // validCert parses a cert chain provided as der argument and verifies the leaf and der[0] // correspond to the private key, the domain and key type match, and expiration dates // are valid. It doesn't do any revocation checking. // // The returned value is the verified leaf cert. func validCert(ck certKey, der [][]byte, key crypto.Signer, now time.Time) (leaf *x509.Certificate, err error) { // parse public part(s) var n int for _, b := range der { n += len(b) } pub := make([]byte, n) n = 0 for _, b := range der { n += copy(pub[n:], b) } x509Cert, err := x509.ParseCertificates(pub) if err != nil || len(x509Cert) == 0 { return nil, errors.New("acme/autocert: no public key found") } // verify the leaf is not expired and matches the domain name leaf = x509Cert[0] if now.Before(leaf.NotBefore) { return nil, errors.New("acme/autocert: certificate is not valid yet") } if now.After(leaf.NotAfter) { return nil, errors.New("acme/autocert: expired certificate") } if err := leaf.VerifyHostname(ck.domain); err != nil { return nil, err } // renew certificates revoked by Let's Encrypt in January 2022 if isRevokedLetsEncrypt(leaf) { return nil, errors.New("acme/autocert: certificate was probably revoked by Let's Encrypt") } // ensure the leaf corresponds to the private key and matches the certKey type switch pub := leaf.PublicKey.(type) { case *rsa.PublicKey: prv, ok := key.(*rsa.PrivateKey) if !ok { return nil, errors.New("acme/autocert: private key type does not match public key type") } if pub.N.Cmp(prv.N) != 0 { return nil, errors.New("acme/autocert: private key does not match public key") } if !ck.isRSA && !ck.isToken { return nil, errors.New("acme/autocert: key type does not match expected value") } case *ecdsa.PublicKey: prv, ok := key.(*ecdsa.PrivateKey) if !ok { return nil, errors.New("acme/autocert: private key type does not match public key type") } if pub.X.Cmp(prv.X) != 0 || pub.Y.Cmp(prv.Y) != 0 { return nil, errors.New("acme/autocert: private key does not match public key") } if ck.isRSA && !ck.isToken { return nil, errors.New("acme/autocert: key type does not match expected value") } default: return nil, errors.New("acme/autocert: unknown public key algorithm") } return leaf, nil } // https://community.letsencrypt.org/t/2022-01-25-issue-with-tls-alpn-01-validation-method/170450 var letsEncryptFixDeployTime = time.Date(2022, time.January, 26, 00, 48, 0, 0, time.UTC) // isRevokedLetsEncrypt returns whether the certificate is likely to be part of // a batch of certificates revoked by Let's Encrypt in January 2022. This check // can be safely removed from May 2022. func isRevokedLetsEncrypt(cert *x509.Certificate) bool { O := cert.Issuer.Organization return len(O) == 1 && O[0] == "Let's Encrypt" && cert.NotBefore.Before(letsEncryptFixDeployTime) } type lockedMathRand struct { sync.Mutex rnd *mathrand.Rand } func (r *lockedMathRand) int63n(max int64) int64 { r.Lock() n := r.rnd.Int63n(max) r.Unlock() return n } // For easier testing. var ( // Called when a state is removed. testDidRemoveState = func(certKey) {} )
crypto/acme/autocert/autocert.go/0
{ "file_path": "crypto/acme/autocert/autocert.go", "repo_id": "crypto", "token_count": 12909 }
0
// 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 acme import ( "crypto" "crypto/x509" "errors" "fmt" "net/http" "strings" "time" ) // ACME status values of Account, Order, Authorization and Challenge objects. // See https://tools.ietf.org/html/rfc8555#section-7.1.6 for details. const ( StatusDeactivated = "deactivated" StatusExpired = "expired" StatusInvalid = "invalid" StatusPending = "pending" StatusProcessing = "processing" StatusReady = "ready" StatusRevoked = "revoked" StatusUnknown = "unknown" StatusValid = "valid" ) // CRLReasonCode identifies the reason for a certificate revocation. type CRLReasonCode int // CRL reason codes as defined in RFC 5280. const ( CRLReasonUnspecified CRLReasonCode = 0 CRLReasonKeyCompromise CRLReasonCode = 1 CRLReasonCACompromise CRLReasonCode = 2 CRLReasonAffiliationChanged CRLReasonCode = 3 CRLReasonSuperseded CRLReasonCode = 4 CRLReasonCessationOfOperation CRLReasonCode = 5 CRLReasonCertificateHold CRLReasonCode = 6 CRLReasonRemoveFromCRL CRLReasonCode = 8 CRLReasonPrivilegeWithdrawn CRLReasonCode = 9 CRLReasonAACompromise CRLReasonCode = 10 ) var ( // ErrUnsupportedKey is returned when an unsupported key type is encountered. ErrUnsupportedKey = errors.New("acme: unknown key type; only RSA and ECDSA are supported") // ErrAccountAlreadyExists indicates that the Client's key has already been registered // with the CA. It is returned by Register method. ErrAccountAlreadyExists = errors.New("acme: account already exists") // ErrNoAccount indicates that the Client's key has not been registered with the CA. ErrNoAccount = errors.New("acme: account does not exist") ) // A Subproblem describes an ACME subproblem as reported in an Error. type Subproblem struct { // Type is a URI reference that identifies the problem type, // typically in a "urn:acme:error:xxx" form. Type string // Detail is a human-readable explanation specific to this occurrence of the problem. Detail string // Instance indicates a URL that the client should direct a human user to visit // in order for instructions on how to agree to the updated Terms of Service. // In such an event CA sets StatusCode to 403, Type to // "urn:ietf:params:acme:error:userActionRequired", and adds a Link header with relation // "terms-of-service" containing the latest TOS URL. Instance string // Identifier may contain the ACME identifier that the error is for. Identifier *AuthzID } func (sp Subproblem) String() string { str := fmt.Sprintf("%s: ", sp.Type) if sp.Identifier != nil { str += fmt.Sprintf("[%s: %s] ", sp.Identifier.Type, sp.Identifier.Value) } str += sp.Detail return str } // Error is an ACME error, defined in Problem Details for HTTP APIs doc // http://tools.ietf.org/html/draft-ietf-appsawg-http-problem. type Error struct { // StatusCode is The HTTP status code generated by the origin server. StatusCode int // ProblemType is a URI reference that identifies the problem type, // typically in a "urn:acme:error:xxx" form. ProblemType string // Detail is a human-readable explanation specific to this occurrence of the problem. Detail string // Instance indicates a URL that the client should direct a human user to visit // in order for instructions on how to agree to the updated Terms of Service. // In such an event CA sets StatusCode to 403, ProblemType to // "urn:ietf:params:acme:error:userActionRequired" and a Link header with relation // "terms-of-service" containing the latest TOS URL. Instance string // Header is the original server error response headers. // It may be nil. Header http.Header // Subproblems may contain more detailed information about the individual problems // that caused the error. This field is only sent by RFC 8555 compatible ACME // servers. Defined in RFC 8555 Section 6.7.1. Subproblems []Subproblem } func (e *Error) Error() string { str := fmt.Sprintf("%d %s: %s", e.StatusCode, e.ProblemType, e.Detail) if len(e.Subproblems) > 0 { str += fmt.Sprintf("; subproblems:") for _, sp := range e.Subproblems { str += fmt.Sprintf("\n\t%s", sp) } } return str } // AuthorizationError indicates that an authorization for an identifier // did not succeed. // It contains all errors from Challenge items of the failed Authorization. type AuthorizationError struct { // URI uniquely identifies the failed Authorization. URI string // Identifier is an AuthzID.Value of the failed Authorization. Identifier string // Errors is a collection of non-nil error values of Challenge items // of the failed Authorization. Errors []error } func (a *AuthorizationError) Error() string { e := make([]string, len(a.Errors)) for i, err := range a.Errors { e[i] = err.Error() } if a.Identifier != "" { return fmt.Sprintf("acme: authorization error for %s: %s", a.Identifier, strings.Join(e, "; ")) } return fmt.Sprintf("acme: authorization error: %s", strings.Join(e, "; ")) } // OrderError is returned from Client's order related methods. // It indicates the order is unusable and the clients should start over with // AuthorizeOrder. // // The clients can still fetch the order object from CA using GetOrder // to inspect its state. type OrderError struct { OrderURL string Status string } func (oe *OrderError) Error() string { return fmt.Sprintf("acme: order %s status: %s", oe.OrderURL, oe.Status) } // RateLimit reports whether err represents a rate limit error and // any Retry-After duration returned by the server. // // See the following for more details on rate limiting: // https://tools.ietf.org/html/draft-ietf-acme-acme-05#section-5.6 func RateLimit(err error) (time.Duration, bool) { e, ok := err.(*Error) if !ok { return 0, false } // Some CA implementations may return incorrect values. // Use case-insensitive comparison. if !strings.HasSuffix(strings.ToLower(e.ProblemType), ":ratelimited") { return 0, false } if e.Header == nil { return 0, true } return retryAfter(e.Header.Get("Retry-After")), true } // Account is a user account. It is associated with a private key. // Non-RFC 8555 fields are empty when interfacing with a compliant CA. type Account struct { // URI is the account unique ID, which is also a URL used to retrieve // account data from the CA. // When interfacing with RFC 8555-compliant CAs, URI is the "kid" field // value in JWS signed requests. URI string // Contact is a slice of contact info used during registration. // See https://tools.ietf.org/html/rfc8555#section-7.3 for supported // formats. Contact []string // Status indicates current account status as returned by the CA. // Possible values are StatusValid, StatusDeactivated, and StatusRevoked. Status string // OrdersURL is a URL from which a list of orders submitted by this account // can be fetched. OrdersURL string // The terms user has agreed to. // A value not matching CurrentTerms indicates that the user hasn't agreed // to the actual Terms of Service of the CA. // // It is non-RFC 8555 compliant. Package users can store the ToS they agree to // during Client's Register call in the prompt callback function. AgreedTerms string // Actual terms of a CA. // // It is non-RFC 8555 compliant. Use Directory's Terms field. // When a CA updates their terms and requires an account agreement, // a URL at which instructions to do so is available in Error's Instance field. CurrentTerms string // Authz is the authorization URL used to initiate a new authz flow. // // It is non-RFC 8555 compliant. Use Directory's AuthzURL or OrderURL. Authz string // Authorizations is a URI from which a list of authorizations // granted to this account can be fetched via a GET request. // // It is non-RFC 8555 compliant and is obsoleted by OrdersURL. Authorizations string // Certificates is a URI from which a list of certificates // issued for this account can be fetched via a GET request. // // It is non-RFC 8555 compliant and is obsoleted by OrdersURL. Certificates string // ExternalAccountBinding represents an arbitrary binding to an account of // the CA which the ACME server is tied to. // See https://tools.ietf.org/html/rfc8555#section-7.3.4 for more details. ExternalAccountBinding *ExternalAccountBinding } // ExternalAccountBinding contains the data needed to form a request with // an external account binding. // See https://tools.ietf.org/html/rfc8555#section-7.3.4 for more details. type ExternalAccountBinding struct { // KID is the Key ID of the symmetric MAC key that the CA provides to // identify an external account from ACME. KID string // Key is the bytes of the symmetric key that the CA provides to identify // the account. Key must correspond to the KID. Key []byte } func (e *ExternalAccountBinding) String() string { return fmt.Sprintf("&{KID: %q, Key: redacted}", e.KID) } // Directory is ACME server discovery data. // See https://tools.ietf.org/html/rfc8555#section-7.1.1 for more details. type Directory struct { // NonceURL indicates an endpoint where to fetch fresh nonce values from. NonceURL string // RegURL is an account endpoint URL, allowing for creating new accounts. // Pre-RFC 8555 CAs also allow modifying existing accounts at this URL. RegURL string // OrderURL is used to initiate the certificate issuance flow // as described in RFC 8555. OrderURL string // AuthzURL is used to initiate identifier pre-authorization flow. // Empty string indicates the flow is unsupported by the CA. AuthzURL string // CertURL is a new certificate issuance endpoint URL. // It is non-RFC 8555 compliant and is obsoleted by OrderURL. CertURL string // RevokeURL is used to initiate a certificate revocation flow. RevokeURL string // KeyChangeURL allows to perform account key rollover flow. KeyChangeURL string // Term is a URI identifying the current terms of service. Terms string // Website is an HTTP or HTTPS URL locating a website // providing more information about the ACME server. Website string // CAA consists of lowercase hostname elements, which the ACME server // recognises as referring to itself for the purposes of CAA record validation // as defined in RFC 6844. CAA []string // ExternalAccountRequired indicates that the CA requires for all account-related // requests to include external account binding information. ExternalAccountRequired bool } // Order represents a client's request for a certificate. // It tracks the request flow progress through to issuance. type Order struct { // URI uniquely identifies an order. URI string // Status represents the current status of the order. // It indicates which action the client should take. // // Possible values are StatusPending, StatusReady, StatusProcessing, StatusValid and StatusInvalid. // Pending means the CA does not believe that the client has fulfilled the requirements. // Ready indicates that the client has fulfilled all the requirements and can submit a CSR // to obtain a certificate. This is done with Client's CreateOrderCert. // Processing means the certificate is being issued. // Valid indicates the CA has issued the certificate. It can be downloaded // from the Order's CertURL. This is done with Client's FetchCert. // Invalid means the certificate will not be issued. Users should consider this order // abandoned. Status string // Expires is the timestamp after which CA considers this order invalid. Expires time.Time // Identifiers contains all identifier objects which the order pertains to. Identifiers []AuthzID // NotBefore is the requested value of the notBefore field in the certificate. NotBefore time.Time // NotAfter is the requested value of the notAfter field in the certificate. NotAfter time.Time // AuthzURLs represents authorizations to complete before a certificate // for identifiers specified in the order can be issued. // It also contains unexpired authorizations that the client has completed // in the past. // // Authorization objects can be fetched using Client's GetAuthorization method. // // The required authorizations are dictated by CA policies. // There may not be a 1:1 relationship between the identifiers and required authorizations. // Required authorizations can be identified by their StatusPending status. // // For orders in the StatusValid or StatusInvalid state these are the authorizations // which were completed. AuthzURLs []string // FinalizeURL is the endpoint at which a CSR is submitted to obtain a certificate // once all the authorizations are satisfied. FinalizeURL string // CertURL points to the certificate that has been issued in response to this order. CertURL string // The error that occurred while processing the order as received from a CA, if any. Error *Error } // OrderOption allows customizing Client.AuthorizeOrder call. type OrderOption interface { privateOrderOpt() } // WithOrderNotBefore sets order's NotBefore field. func WithOrderNotBefore(t time.Time) OrderOption { return orderNotBeforeOpt(t) } // WithOrderNotAfter sets order's NotAfter field. func WithOrderNotAfter(t time.Time) OrderOption { return orderNotAfterOpt(t) } type orderNotBeforeOpt time.Time func (orderNotBeforeOpt) privateOrderOpt() {} type orderNotAfterOpt time.Time func (orderNotAfterOpt) privateOrderOpt() {} // Authorization encodes an authorization response. type Authorization struct { // URI uniquely identifies a authorization. URI string // Status is the current status of an authorization. // Possible values are StatusPending, StatusValid, StatusInvalid, StatusDeactivated, // StatusExpired and StatusRevoked. Status string // Identifier is what the account is authorized to represent. Identifier AuthzID // The timestamp after which the CA considers the authorization invalid. Expires time.Time // Wildcard is true for authorizations of a wildcard domain name. Wildcard bool // Challenges that the client needs to fulfill in order to prove possession // of the identifier (for pending authorizations). // For valid authorizations, the challenge that was validated. // For invalid authorizations, the challenge that was attempted and failed. // // RFC 8555 compatible CAs require users to fuflfill only one of the challenges. Challenges []*Challenge // A collection of sets of challenges, each of which would be sufficient // to prove possession of the identifier. // Clients must complete a set of challenges that covers at least one set. // Challenges are identified by their indices in the challenges array. // If this field is empty, the client needs to complete all challenges. // // This field is unused in RFC 8555. Combinations [][]int } // AuthzID is an identifier that an account is authorized to represent. type AuthzID struct { Type string // The type of identifier, "dns" or "ip". Value string // The identifier itself, e.g. "example.org". } // DomainIDs creates a slice of AuthzID with "dns" identifier type. func DomainIDs(names ...string) []AuthzID { a := make([]AuthzID, len(names)) for i, v := range names { a[i] = AuthzID{Type: "dns", Value: v} } return a } // IPIDs creates a slice of AuthzID with "ip" identifier type. // Each element of addr is textual form of an address as defined // in RFC 1123 Section 2.1 for IPv4 and in RFC 5952 Section 4 for IPv6. func IPIDs(addr ...string) []AuthzID { a := make([]AuthzID, len(addr)) for i, v := range addr { a[i] = AuthzID{Type: "ip", Value: v} } return a } // wireAuthzID is ACME JSON representation of authorization identifier objects. type wireAuthzID struct { Type string `json:"type"` Value string `json:"value"` } // wireAuthz is ACME JSON representation of Authorization objects. type wireAuthz struct { Identifier wireAuthzID Status string Expires time.Time Wildcard bool Challenges []wireChallenge Combinations [][]int Error *wireError } func (z *wireAuthz) authorization(uri string) *Authorization { a := &Authorization{ URI: uri, Status: z.Status, Identifier: AuthzID{Type: z.Identifier.Type, Value: z.Identifier.Value}, Expires: z.Expires, Wildcard: z.Wildcard, Challenges: make([]*Challenge, len(z.Challenges)), Combinations: z.Combinations, // shallow copy } for i, v := range z.Challenges { a.Challenges[i] = v.challenge() } return a } func (z *wireAuthz) error(uri string) *AuthorizationError { err := &AuthorizationError{ URI: uri, Identifier: z.Identifier.Value, } if z.Error != nil { err.Errors = append(err.Errors, z.Error.error(nil)) } for _, raw := range z.Challenges { if raw.Error != nil { err.Errors = append(err.Errors, raw.Error.error(nil)) } } return err } // Challenge encodes a returned CA challenge. // Its Error field may be non-nil if the challenge is part of an Authorization // with StatusInvalid. type Challenge struct { // Type is the challenge type, e.g. "http-01", "tls-alpn-01", "dns-01". Type string // URI is where a challenge response can be posted to. URI string // Token is a random value that uniquely identifies the challenge. Token string // Status identifies the status of this challenge. // In RFC 8555, possible values are StatusPending, StatusProcessing, StatusValid, // and StatusInvalid. Status string // Validated is the time at which the CA validated this challenge. // Always zero value in pre-RFC 8555. Validated time.Time // Error indicates the reason for an authorization failure // when this challenge was used. // The type of a non-nil value is *Error. Error error } // wireChallenge is ACME JSON challenge representation. type wireChallenge struct { URL string `json:"url"` // RFC URI string `json:"uri"` // pre-RFC Type string Token string Status string Validated time.Time Error *wireError } func (c *wireChallenge) challenge() *Challenge { v := &Challenge{ URI: c.URL, Type: c.Type, Token: c.Token, Status: c.Status, } if v.URI == "" { v.URI = c.URI // c.URL was empty; use legacy } if v.Status == "" { v.Status = StatusPending } if c.Error != nil { v.Error = c.Error.error(nil) } return v } // wireError is a subset of fields of the Problem Details object // as described in https://tools.ietf.org/html/rfc7807#section-3.1. type wireError struct { Status int Type string Detail string Instance string Subproblems []Subproblem } func (e *wireError) error(h http.Header) *Error { err := &Error{ StatusCode: e.Status, ProblemType: e.Type, Detail: e.Detail, Instance: e.Instance, Header: h, Subproblems: e.Subproblems, } return err } // CertOption is an optional argument type for the TLS ChallengeCert methods for // customizing a temporary certificate for TLS-based challenges. type CertOption interface { privateCertOpt() } // WithKey creates an option holding a private/public key pair. // The private part signs a certificate, and the public part represents the signee. func WithKey(key crypto.Signer) CertOption { return &certOptKey{key} } type certOptKey struct { key crypto.Signer } func (*certOptKey) privateCertOpt() {} // WithTemplate creates an option for specifying a certificate template. // See x509.CreateCertificate for template usage details. // // In TLS ChallengeCert methods, the template is also used as parent, // resulting in a self-signed certificate. // The DNSNames field of t is always overwritten for tls-sni challenge certs. func WithTemplate(t *x509.Certificate) CertOption { return (*certOptTemplate)(t) } type certOptTemplate x509.Certificate func (*certOptTemplate) privateCertOpt() {}
crypto/acme/types.go/0
{ "file_path": "crypto/acme/types.go", "repo_id": "crypto", "token_count": 5943 }
1
// 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 blake2b import ( "encoding/binary" "math/bits" ) // the precomputed values for BLAKE2b // there are 12 16-byte arrays - one for each round // the entries are calculated from the sigma constants. var precomputed = [12][16]byte{ {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, {11, 12, 5, 15, 8, 0, 2, 13, 10, 3, 7, 9, 14, 6, 1, 4}, {7, 3, 13, 11, 9, 1, 12, 14, 2, 5, 4, 15, 6, 10, 0, 8}, {9, 5, 2, 10, 0, 7, 4, 15, 14, 11, 6, 3, 1, 12, 8, 13}, {2, 6, 0, 8, 12, 10, 11, 3, 4, 7, 15, 1, 13, 5, 14, 9}, {12, 1, 14, 4, 5, 15, 13, 10, 0, 6, 9, 8, 7, 3, 2, 11}, {13, 7, 12, 3, 11, 14, 1, 9, 5, 15, 8, 2, 0, 4, 6, 10}, {6, 14, 11, 0, 15, 9, 3, 8, 12, 13, 1, 10, 2, 7, 4, 5}, {10, 8, 7, 1, 2, 4, 6, 5, 15, 9, 3, 13, 11, 14, 12, 0}, {0, 2, 4, 6, 1, 3, 5, 7, 8, 10, 12, 14, 9, 11, 13, 15}, // equal to the first {14, 4, 9, 13, 10, 8, 15, 6, 1, 0, 11, 5, 12, 2, 7, 3}, // equal to the second } func hashBlocksGeneric(h *[8]uint64, c *[2]uint64, flag uint64, blocks []byte) { var m [16]uint64 c0, c1 := c[0], c[1] for i := 0; i < len(blocks); { c0 += BlockSize if c0 < BlockSize { c1++ } v0, v1, v2, v3, v4, v5, v6, v7 := h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7] v8, v9, v10, v11, v12, v13, v14, v15 := iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], iv[6], iv[7] v12 ^= c0 v13 ^= c1 v14 ^= flag for j := range m { m[j] = binary.LittleEndian.Uint64(blocks[i:]) i += 8 } for j := range precomputed { s := &(precomputed[j]) v0 += m[s[0]] v0 += v4 v12 ^= v0 v12 = bits.RotateLeft64(v12, -32) v8 += v12 v4 ^= v8 v4 = bits.RotateLeft64(v4, -24) v1 += m[s[1]] v1 += v5 v13 ^= v1 v13 = bits.RotateLeft64(v13, -32) v9 += v13 v5 ^= v9 v5 = bits.RotateLeft64(v5, -24) v2 += m[s[2]] v2 += v6 v14 ^= v2 v14 = bits.RotateLeft64(v14, -32) v10 += v14 v6 ^= v10 v6 = bits.RotateLeft64(v6, -24) v3 += m[s[3]] v3 += v7 v15 ^= v3 v15 = bits.RotateLeft64(v15, -32) v11 += v15 v7 ^= v11 v7 = bits.RotateLeft64(v7, -24) v0 += m[s[4]] v0 += v4 v12 ^= v0 v12 = bits.RotateLeft64(v12, -16) v8 += v12 v4 ^= v8 v4 = bits.RotateLeft64(v4, -63) v1 += m[s[5]] v1 += v5 v13 ^= v1 v13 = bits.RotateLeft64(v13, -16) v9 += v13 v5 ^= v9 v5 = bits.RotateLeft64(v5, -63) v2 += m[s[6]] v2 += v6 v14 ^= v2 v14 = bits.RotateLeft64(v14, -16) v10 += v14 v6 ^= v10 v6 = bits.RotateLeft64(v6, -63) v3 += m[s[7]] v3 += v7 v15 ^= v3 v15 = bits.RotateLeft64(v15, -16) v11 += v15 v7 ^= v11 v7 = bits.RotateLeft64(v7, -63) v0 += m[s[8]] v0 += v5 v15 ^= v0 v15 = bits.RotateLeft64(v15, -32) v10 += v15 v5 ^= v10 v5 = bits.RotateLeft64(v5, -24) v1 += m[s[9]] v1 += v6 v12 ^= v1 v12 = bits.RotateLeft64(v12, -32) v11 += v12 v6 ^= v11 v6 = bits.RotateLeft64(v6, -24) v2 += m[s[10]] v2 += v7 v13 ^= v2 v13 = bits.RotateLeft64(v13, -32) v8 += v13 v7 ^= v8 v7 = bits.RotateLeft64(v7, -24) v3 += m[s[11]] v3 += v4 v14 ^= v3 v14 = bits.RotateLeft64(v14, -32) v9 += v14 v4 ^= v9 v4 = bits.RotateLeft64(v4, -24) v0 += m[s[12]] v0 += v5 v15 ^= v0 v15 = bits.RotateLeft64(v15, -16) v10 += v15 v5 ^= v10 v5 = bits.RotateLeft64(v5, -63) v1 += m[s[13]] v1 += v6 v12 ^= v1 v12 = bits.RotateLeft64(v12, -16) v11 += v12 v6 ^= v11 v6 = bits.RotateLeft64(v6, -63) v2 += m[s[14]] v2 += v7 v13 ^= v2 v13 = bits.RotateLeft64(v13, -16) v8 += v13 v7 ^= v8 v7 = bits.RotateLeft64(v7, -63) v3 += m[s[15]] v3 += v4 v14 ^= v3 v14 = bits.RotateLeft64(v14, -16) v9 += v14 v4 ^= v9 v4 = bits.RotateLeft64(v4, -63) } h[0] ^= v0 ^ v8 h[1] ^= v1 ^ v9 h[2] ^= v2 ^ v10 h[3] ^= v3 ^ v11 h[4] ^= v4 ^ v12 h[5] ^= v5 ^ v13 h[6] ^= v6 ^ v14 h[7] ^= v7 ^ v15 } c[0], c[1] = c0, c1 }
crypto/blake2b/blake2b_generic.go/0
{ "file_path": "crypto/blake2b/blake2b_generic.go", "repo_id": "crypto", "token_count": 2459 }
2
// Copyright 2010 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 blowfish implements Bruce Schneier's Blowfish encryption algorithm. // // Blowfish is a legacy cipher and its short block size makes it vulnerable to // birthday bound attacks (see https://sweet32.info). It should only be used // where compatibility with legacy systems, not security, is the goal. // // Deprecated: any new system should use AES (from crypto/aes, if necessary in // an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from // golang.org/x/crypto/chacha20poly1305). package blowfish // The code is a port of Bruce Schneier's C implementation. // See https://www.schneier.com/blowfish.html. import "strconv" // The Blowfish block size in bytes. const BlockSize = 8 // A Cipher is an instance of Blowfish encryption using a particular key. type Cipher struct { p [18]uint32 s0, s1, s2, s3 [256]uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a Cipher. // The key argument should be the Blowfish key, from 1 to 56 bytes. func NewCipher(key []byte) (*Cipher, error) { var result Cipher if k := len(key); k < 1 || k > 56 { return nil, KeySizeError(k) } initCipher(&result) ExpandKey(key, &result) return &result, nil } // NewSaltedCipher creates a returns a Cipher that folds a salt into its key // schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is // sufficient and desirable. For bcrypt compatibility, the key can be over 56 // bytes. func NewSaltedCipher(key, salt []byte) (*Cipher, error) { if len(salt) == 0 { return NewCipher(key) } var result Cipher if k := len(key); k < 1 { return nil, KeySizeError(k) } initCipher(&result) expandKeyWithSalt(key, salt, &result) return &result, nil } // BlockSize returns the Blowfish block size, 8 bytes. // It is necessary to satisfy the Block interface in the // package "crypto/cipher". func (c *Cipher) BlockSize() int { return BlockSize } // Encrypt encrypts the 8-byte buffer src using the key k // and stores the result in dst. // Note that for amounts of data larger than a block, // it is not safe to just call Encrypt on successive blocks; // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). func (c *Cipher) Encrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = encryptBlock(l, r, c) dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) } // Decrypt decrypts the 8-byte buffer src using the key k // and stores the result in dst. func (c *Cipher) Decrypt(dst, src []byte) { l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) l, r = decryptBlock(l, r, c) dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r) } func initCipher(c *Cipher) { copy(c.p[0:], p[0:]) copy(c.s0[0:], s0[0:]) copy(c.s1[0:], s1[0:]) copy(c.s2[0:], s2[0:]) copy(c.s3[0:], s3[0:]) }
crypto/blowfish/cipher.go/0
{ "file_path": "crypto/blowfish/cipher.go", "repo_id": "crypto", "token_count": 1299 }
3
// 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 chacha20 implements the ChaCha20 and XChaCha20 encryption algorithms // as specified in RFC 8439 and draft-irtf-cfrg-xchacha-01. package chacha20 import ( "crypto/cipher" "encoding/binary" "errors" "math/bits" "golang.org/x/crypto/internal/alias" ) const ( // KeySize is the size of the key used by this cipher, in bytes. KeySize = 32 // NonceSize is the size of the nonce used with the standard variant of this // cipher, in bytes. // // Note that this is too short to be safely generated at random if the same // key is reused more than 2³² times. NonceSize = 12 // NonceSizeX is the size of the nonce used with the XChaCha20 variant of // this cipher, in bytes. NonceSizeX = 24 ) // Cipher is a stateful instance of ChaCha20 or XChaCha20 using a particular key // and nonce. A *Cipher implements the cipher.Stream interface. type Cipher struct { // The ChaCha20 state is 16 words: 4 constant, 8 of key, 1 of counter // (incremented after each block), and 3 of nonce. key [8]uint32 counter uint32 nonce [3]uint32 // The last len bytes of buf are leftover key stream bytes from the previous // XORKeyStream invocation. The size of buf depends on how many blocks are // computed at a time by xorKeyStreamBlocks. buf [bufSize]byte len int // overflow is set when the counter overflowed, no more blocks can be // generated, and the next XORKeyStream call should panic. overflow bool // The counter-independent results of the first round are cached after they // are computed the first time. precompDone bool p1, p5, p9, p13 uint32 p2, p6, p10, p14 uint32 p3, p7, p11, p15 uint32 } var _ cipher.Stream = (*Cipher)(nil) // NewUnauthenticatedCipher creates a new ChaCha20 stream cipher with the given // 32 bytes key and a 12 or 24 bytes nonce. If a nonce of 24 bytes is provided, // the XChaCha20 construction will be used. It returns an error if key or nonce // have any other length. // // Note that ChaCha20, like all stream ciphers, is not authenticated and allows // attackers to silently tamper with the plaintext. For this reason, it is more // appropriate as a building block than as a standalone encryption mechanism. // Instead, consider using package golang.org/x/crypto/chacha20poly1305. func NewUnauthenticatedCipher(key, nonce []byte) (*Cipher, error) { // This function is split into a wrapper so that the Cipher allocation will // be inlined, and depending on how the caller uses the return value, won't // escape to the heap. c := &Cipher{} return newUnauthenticatedCipher(c, key, nonce) } func newUnauthenticatedCipher(c *Cipher, key, nonce []byte) (*Cipher, error) { if len(key) != KeySize { return nil, errors.New("chacha20: wrong key size") } if len(nonce) == NonceSizeX { // XChaCha20 uses the ChaCha20 core to mix 16 bytes of the nonce into a // derived key, allowing it to operate on a nonce of 24 bytes. See // draft-irtf-cfrg-xchacha-01, Section 2.3. key, _ = HChaCha20(key, nonce[0:16]) cNonce := make([]byte, NonceSize) copy(cNonce[4:12], nonce[16:24]) nonce = cNonce } else if len(nonce) != NonceSize { return nil, errors.New("chacha20: wrong nonce size") } key, nonce = key[:KeySize], nonce[:NonceSize] // bounds check elimination hint c.key = [8]uint32{ binary.LittleEndian.Uint32(key[0:4]), binary.LittleEndian.Uint32(key[4:8]), binary.LittleEndian.Uint32(key[8:12]), binary.LittleEndian.Uint32(key[12:16]), binary.LittleEndian.Uint32(key[16:20]), binary.LittleEndian.Uint32(key[20:24]), binary.LittleEndian.Uint32(key[24:28]), binary.LittleEndian.Uint32(key[28:32]), } c.nonce = [3]uint32{ binary.LittleEndian.Uint32(nonce[0:4]), binary.LittleEndian.Uint32(nonce[4:8]), binary.LittleEndian.Uint32(nonce[8:12]), } return c, nil } // The constant first 4 words of the ChaCha20 state. const ( j0 uint32 = 0x61707865 // expa j1 uint32 = 0x3320646e // nd 3 j2 uint32 = 0x79622d32 // 2-by j3 uint32 = 0x6b206574 // te k ) const blockSize = 64 // quarterRound is the core of ChaCha20. It shuffles the bits of 4 state words. // It's executed 4 times for each of the 20 ChaCha20 rounds, operating on all 16 // words each round, in columnar or diagonal groups of 4 at a time. func quarterRound(a, b, c, d uint32) (uint32, uint32, uint32, uint32) { a += b d ^= a d = bits.RotateLeft32(d, 16) c += d b ^= c b = bits.RotateLeft32(b, 12) a += b d ^= a d = bits.RotateLeft32(d, 8) c += d b ^= c b = bits.RotateLeft32(b, 7) return a, b, c, d } // SetCounter sets the Cipher counter. The next invocation of XORKeyStream will // behave as if (64 * counter) bytes had been encrypted so far. // // To prevent accidental counter reuse, SetCounter panics if counter is less // than the current value. // // Note that the execution time of XORKeyStream is not independent of the // counter value. func (s *Cipher) SetCounter(counter uint32) { // Internally, s may buffer multiple blocks, which complicates this // implementation slightly. When checking whether the counter has rolled // back, we must use both s.counter and s.len to determine how many blocks // we have already output. outputCounter := s.counter - uint32(s.len)/blockSize if s.overflow || counter < outputCounter { panic("chacha20: SetCounter attempted to rollback counter") } // In the general case, we set the new counter value and reset s.len to 0, // causing the next call to XORKeyStream to refill the buffer. However, if // we're advancing within the existing buffer, we can save work by simply // setting s.len. if counter < s.counter { s.len = int(s.counter-counter) * blockSize } else { s.counter = counter s.len = 0 } } // XORKeyStream XORs each byte in the given slice with a byte from the // cipher's key stream. Dst and src must overlap entirely or not at all. // // If len(dst) < len(src), XORKeyStream will panic. It is acceptable // to pass a dst bigger than src, and in that case, XORKeyStream will // only update dst[:len(src)] and will not touch the rest of dst. // // Multiple calls to XORKeyStream behave as if the concatenation of // the src buffers was passed in a single run. That is, Cipher // maintains state and does not reset at each XORKeyStream call. func (s *Cipher) XORKeyStream(dst, src []byte) { if len(src) == 0 { return } if len(dst) < len(src) { panic("chacha20: output smaller than input") } dst = dst[:len(src)] if alias.InexactOverlap(dst, src) { panic("chacha20: invalid buffer overlap") } // First, drain any remaining key stream from a previous XORKeyStream. if s.len != 0 { keyStream := s.buf[bufSize-s.len:] if len(src) < len(keyStream) { keyStream = keyStream[:len(src)] } _ = src[len(keyStream)-1] // bounds check elimination hint for i, b := range keyStream { dst[i] = src[i] ^ b } s.len -= len(keyStream) dst, src = dst[len(keyStream):], src[len(keyStream):] } if len(src) == 0 { return } // If we'd need to let the counter overflow and keep generating output, // panic immediately. If instead we'd only reach the last block, remember // not to generate any more output after the buffer is drained. numBlocks := (uint64(len(src)) + blockSize - 1) / blockSize if s.overflow || uint64(s.counter)+numBlocks > 1<<32 { panic("chacha20: counter overflow") } else if uint64(s.counter)+numBlocks == 1<<32 { s.overflow = true } // xorKeyStreamBlocks implementations expect input lengths that are a // multiple of bufSize. Platform-specific ones process multiple blocks at a // time, so have bufSizes that are a multiple of blockSize. full := len(src) - len(src)%bufSize if full > 0 { s.xorKeyStreamBlocks(dst[:full], src[:full]) } dst, src = dst[full:], src[full:] // If using a multi-block xorKeyStreamBlocks would overflow, use the generic // one that does one block at a time. const blocksPerBuf = bufSize / blockSize if uint64(s.counter)+blocksPerBuf > 1<<32 { s.buf = [bufSize]byte{} numBlocks := (len(src) + blockSize - 1) / blockSize buf := s.buf[bufSize-numBlocks*blockSize:] copy(buf, src) s.xorKeyStreamBlocksGeneric(buf, buf) s.len = len(buf) - copy(dst, buf) return } // If we have a partial (multi-)block, pad it for xorKeyStreamBlocks, and // keep the leftover keystream for the next XORKeyStream invocation. if len(src) > 0 { s.buf = [bufSize]byte{} copy(s.buf[:], src) s.xorKeyStreamBlocks(s.buf[:], s.buf[:]) s.len = bufSize - copy(dst, s.buf[:]) } } func (s *Cipher) xorKeyStreamBlocksGeneric(dst, src []byte) { if len(dst) != len(src) || len(dst)%blockSize != 0 { panic("chacha20: internal error: wrong dst and/or src length") } // To generate each block of key stream, the initial cipher state // (represented below) is passed through 20 rounds of shuffling, // alternatively applying quarterRounds by columns (like 1, 5, 9, 13) // or by diagonals (like 1, 6, 11, 12). // // 0:cccccccc 1:cccccccc 2:cccccccc 3:cccccccc // 4:kkkkkkkk 5:kkkkkkkk 6:kkkkkkkk 7:kkkkkkkk // 8:kkkkkkkk 9:kkkkkkkk 10:kkkkkkkk 11:kkkkkkkk // 12:bbbbbbbb 13:nnnnnnnn 14:nnnnnnnn 15:nnnnnnnn // // c=constant k=key b=blockcount n=nonce var ( c0, c1, c2, c3 = j0, j1, j2, j3 c4, c5, c6, c7 = s.key[0], s.key[1], s.key[2], s.key[3] c8, c9, c10, c11 = s.key[4], s.key[5], s.key[6], s.key[7] _, c13, c14, c15 = s.counter, s.nonce[0], s.nonce[1], s.nonce[2] ) // Three quarters of the first round don't depend on the counter, so we can // calculate them here, and reuse them for multiple blocks in the loop, and // for future XORKeyStream invocations. if !s.precompDone { s.p1, s.p5, s.p9, s.p13 = quarterRound(c1, c5, c9, c13) s.p2, s.p6, s.p10, s.p14 = quarterRound(c2, c6, c10, c14) s.p3, s.p7, s.p11, s.p15 = quarterRound(c3, c7, c11, c15) s.precompDone = true } // A condition of len(src) > 0 would be sufficient, but this also // acts as a bounds check elimination hint. for len(src) >= 64 && len(dst) >= 64 { // The remainder of the first column round. fcr0, fcr4, fcr8, fcr12 := quarterRound(c0, c4, c8, s.counter) // The second diagonal round. x0, x5, x10, x15 := quarterRound(fcr0, s.p5, s.p10, s.p15) x1, x6, x11, x12 := quarterRound(s.p1, s.p6, s.p11, fcr12) x2, x7, x8, x13 := quarterRound(s.p2, s.p7, fcr8, s.p13) x3, x4, x9, x14 := quarterRound(s.p3, fcr4, s.p9, s.p14) // The remaining 18 rounds. for i := 0; i < 9; i++ { // Column round. x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) // Diagonal round. x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) } // Add back the initial state to generate the key stream, then // XOR the key stream with the source and write out the result. addXor(dst[0:4], src[0:4], x0, c0) addXor(dst[4:8], src[4:8], x1, c1) addXor(dst[8:12], src[8:12], x2, c2) addXor(dst[12:16], src[12:16], x3, c3) addXor(dst[16:20], src[16:20], x4, c4) addXor(dst[20:24], src[20:24], x5, c5) addXor(dst[24:28], src[24:28], x6, c6) addXor(dst[28:32], src[28:32], x7, c7) addXor(dst[32:36], src[32:36], x8, c8) addXor(dst[36:40], src[36:40], x9, c9) addXor(dst[40:44], src[40:44], x10, c10) addXor(dst[44:48], src[44:48], x11, c11) addXor(dst[48:52], src[48:52], x12, s.counter) addXor(dst[52:56], src[52:56], x13, c13) addXor(dst[56:60], src[56:60], x14, c14) addXor(dst[60:64], src[60:64], x15, c15) s.counter += 1 src, dst = src[blockSize:], dst[blockSize:] } } // HChaCha20 uses the ChaCha20 core to generate a derived key from a 32 bytes // key and a 16 bytes nonce. It returns an error if key or nonce have any other // length. It is used as part of the XChaCha20 construction. func HChaCha20(key, nonce []byte) ([]byte, error) { // This function is split into a wrapper so that the slice allocation will // be inlined, and depending on how the caller uses the return value, won't // escape to the heap. out := make([]byte, 32) return hChaCha20(out, key, nonce) } func hChaCha20(out, key, nonce []byte) ([]byte, error) { if len(key) != KeySize { return nil, errors.New("chacha20: wrong HChaCha20 key size") } if len(nonce) != 16 { return nil, errors.New("chacha20: wrong HChaCha20 nonce size") } x0, x1, x2, x3 := j0, j1, j2, j3 x4 := binary.LittleEndian.Uint32(key[0:4]) x5 := binary.LittleEndian.Uint32(key[4:8]) x6 := binary.LittleEndian.Uint32(key[8:12]) x7 := binary.LittleEndian.Uint32(key[12:16]) x8 := binary.LittleEndian.Uint32(key[16:20]) x9 := binary.LittleEndian.Uint32(key[20:24]) x10 := binary.LittleEndian.Uint32(key[24:28]) x11 := binary.LittleEndian.Uint32(key[28:32]) x12 := binary.LittleEndian.Uint32(nonce[0:4]) x13 := binary.LittleEndian.Uint32(nonce[4:8]) x14 := binary.LittleEndian.Uint32(nonce[8:12]) x15 := binary.LittleEndian.Uint32(nonce[12:16]) for i := 0; i < 10; i++ { // Diagonal round. x0, x4, x8, x12 = quarterRound(x0, x4, x8, x12) x1, x5, x9, x13 = quarterRound(x1, x5, x9, x13) x2, x6, x10, x14 = quarterRound(x2, x6, x10, x14) x3, x7, x11, x15 = quarterRound(x3, x7, x11, x15) // Column round. x0, x5, x10, x15 = quarterRound(x0, x5, x10, x15) x1, x6, x11, x12 = quarterRound(x1, x6, x11, x12) x2, x7, x8, x13 = quarterRound(x2, x7, x8, x13) x3, x4, x9, x14 = quarterRound(x3, x4, x9, x14) } _ = out[31] // bounds check elimination hint binary.LittleEndian.PutUint32(out[0:4], x0) binary.LittleEndian.PutUint32(out[4:8], x1) binary.LittleEndian.PutUint32(out[8:12], x2) binary.LittleEndian.PutUint32(out[12:16], x3) binary.LittleEndian.PutUint32(out[16:20], x12) binary.LittleEndian.PutUint32(out[20:24], x13) binary.LittleEndian.PutUint32(out[24:28], x14) binary.LittleEndian.PutUint32(out[28:32], x15) return out, nil }
crypto/chacha20/chacha_generic.go/0
{ "file_path": "crypto/chacha20/chacha_generic.go", "repo_id": "crypto", "token_count": 5714 }
4