├── README.md ├── cmd └── complexity │ └── main.go ├── complexity.go ├── complexity_test.go ├── go.mod ├── go.sum ├── plugin └── main.go ├── testdata └── src │ ├── a │ └── a.go │ └── halstead │ ├── a.go │ └── b.go └── vendor ├── golang.org └── x │ ├── mod │ ├── LICENSE │ ├── PATENTS │ ├── internal │ │ └── lazyregexp │ │ │ └── lazyre.go │ ├── modfile │ │ ├── print.go │ │ ├── read.go │ │ ├── rule.go │ │ └── work.go │ ├── module │ │ ├── module.go │ │ └── pseudo.go │ └── semver │ │ └── semver.go │ ├── sync │ ├── LICENSE │ ├── PATENTS │ └── errgroup │ │ ├── errgroup.go │ │ ├── go120.go │ │ └── pre_go120.go │ └── tools │ ├── LICENSE │ ├── PATENTS │ ├── go │ ├── analysis │ │ ├── analysis.go │ │ ├── analysistest │ │ │ └── analysistest.go │ │ ├── diagnostic.go │ │ ├── doc.go │ │ ├── internal │ │ │ ├── analysisflags │ │ │ │ ├── flags.go │ │ │ │ ├── help.go │ │ │ │ └── url.go │ │ │ └── checker │ │ │ │ └── checker.go │ │ ├── passes │ │ │ └── inspect │ │ │ │ └── inspect.go │ │ ├── unitchecker │ │ │ └── unitchecker.go │ │ └── validate.go │ ├── ast │ │ └── inspector │ │ │ ├── inspector.go │ │ │ ├── iter.go │ │ │ └── typeof.go │ ├── gcexportdata │ │ ├── gcexportdata.go │ │ └── importer.go │ ├── packages │ │ ├── doc.go │ │ ├── external.go │ │ ├── golist.go │ │ ├── golist_overlay.go │ │ ├── loadmode_string.go │ │ ├── packages.go │ │ └── visit.go │ └── types │ │ ├── objectpath │ │ └── objectpath.go │ │ └── typeutil │ │ ├── callee.go │ │ ├── imports.go │ │ ├── map.go │ │ ├── methodsetcache.go │ │ └── ui.go │ ├── internal │ ├── aliases │ │ ├── aliases.go │ │ └── aliases_go122.go │ ├── analysisinternal │ │ ├── analysis.go │ │ └── extractdoc.go │ ├── diff │ │ ├── diff.go │ │ ├── lcs │ │ │ ├── common.go │ │ │ ├── doc.go │ │ │ ├── git.sh │ │ │ ├── labels.go │ │ │ ├── old.go │ │ │ └── sequence.go │ │ ├── ndiff.go │ │ └── unified.go │ ├── event │ │ ├── core │ │ │ ├── event.go │ │ │ ├── export.go │ │ │ └── fast.go │ │ ├── doc.go │ │ ├── event.go │ │ ├── keys │ │ │ ├── keys.go │ │ │ ├── standard.go │ │ │ └── util.go │ │ └── label │ │ │ └── label.go │ ├── facts │ │ ├── facts.go │ │ └── imports.go │ ├── gcimporter │ │ ├── bimport.go │ │ ├── exportdata.go │ │ ├── gcimporter.go │ │ ├── iexport.go │ │ ├── iimport.go │ │ ├── iimport_go122.go │ │ ├── predeclared.go │ │ └── ureader_yes.go │ ├── gocommand │ │ ├── invoke.go │ │ ├── vendor.go │ │ └── version.go │ ├── goroot │ │ └── importcfg.go │ ├── packagesinternal │ │ └── packages.go │ ├── pkgbits │ │ ├── codes.go │ │ ├── decoder.go │ │ ├── doc.go │ │ ├── encoder.go │ │ ├── flags.go │ │ ├── reloc.go │ │ ├── support.go │ │ ├── sync.go │ │ ├── syncmarker_string.go │ │ └── version.go │ ├── robustio │ │ ├── gopls_windows.go │ │ ├── robustio.go │ │ ├── robustio_darwin.go │ │ ├── robustio_flaky.go │ │ ├── robustio_other.go │ │ ├── robustio_plan9.go │ │ ├── robustio_posix.go │ │ └── robustio_windows.go │ ├── stdlib │ │ ├── manifest.go │ │ └── stdlib.go │ ├── testenv │ │ ├── exec.go │ │ ├── testenv.go │ │ ├── testenv_notunix.go │ │ └── testenv_unix.go │ ├── typeparams │ │ ├── common.go │ │ ├── coretype.go │ │ ├── free.go │ │ ├── normalize.go │ │ ├── termlist.go │ │ └── typeterm.go │ ├── typesinternal │ │ ├── element.go │ │ ├── errorcode.go │ │ ├── errorcode_string.go │ │ ├── recv.go │ │ ├── toonew.go │ │ └── types.go │ └── versions │ │ ├── constraint.go │ │ ├── constraint_go121.go │ │ ├── features.go │ │ ├── gover.go │ │ ├── types.go │ │ └── versions.go │ └── txtar │ ├── archive.go │ └── fs.go └── modules.txt /README.md: -------------------------------------------------------------------------------- 1 | # go-complexity-analysis 2 | go-complexity-analysis calculates the Cyclomatic complexities, the Halstead complexities and the Maintainability indices of golang functions. 3 | 4 | !! This is a refactored and brought to perfection fork of [shoooooman/go-complexity-analysis-action](https://github.com/shoooooman/go-complexity-analysis). Put star on his repo too! 5 | 6 | # Install 7 | ```sh 8 | $ go install github.com/rauzh/go-complexity-analysis/cmd/complexity@latest 9 | ``` 10 | 11 | # Usage 12 | ```sh 13 | $ go vet -vettool=$(which complexity) [flags] [directory/file] 14 | ``` 15 | 16 | ## Flags 17 | `--cycloover`: show functions with the Cyclomatic complexity > N (default: 10) 18 | `--halsteadover`: show functions with the Cyclomatic complexity > N (default: 50) 19 | `--maintunder`: show functions with the Maintainability index < N (default: 20) 20 | `--verbose`: show all functions complexity info 21 | 22 | ## Output 23 | ``` 24 | ::: func seems to be complex (cyclomatic complexity=) 25 | ::: func seems to have low maintainability (maintainability index=) 26 | ``` 27 | 28 | ## Examples 29 | ```go 30 | $ go vet -vettool=$(which complexity) --cycloover 10 ./... 31 | $ go vet -vettool=$(which complexity) --maintunder 20 main.go 32 | $ go vet -vettool=$(which complexity) --cycloover 5 --maintunder 30 ./src 33 | ``` 34 | 35 | # Metrics 36 | ## Cyclomatic Complexity 37 | The Cyclomatic complexity indicates the complexity of a program. 38 | 39 | This program calculates the complexities of each function by counting idependent paths with the following rules. 40 | ``` 41 | Initial value: 1 42 | +1: if, for, case, ||, && 43 | ``` 44 | 45 | ## Halstead Metrics 46 | 47 | Calculation of each Halstead metrics can be found [here](https://www.verifysoft.com/en_halstead_metrics.html). 48 | 49 | ### Rules 50 | 1. Comments are not considered in Halstead Metrics 51 | 2. Operands and Operators are divided as follows: 52 | 53 | #### Operands 54 | - [Identifiers](!https://golang.org/ref/spec#Identifiers) 55 | - [Constants](!https://golang.org/ref/spec#Constants) 56 | - [Variables](!https://golang.org/ref/spec#Variables) 57 | 58 | #### Operators 59 | - [Operators](!https://golang.org/ref/spec#Operators_and_punctuation) 60 | - Parenthesis, such as "()", is counted as one operator 61 | - [Keywords](!https://golang.org/ref/spec#Keywords) 62 | 63 | ## Maintainability Index 64 | The Maintainability index represents maintainability of a program. 65 | 66 | The value is calculated with the Cyclomatic complexity and the Halstead volume by using the following formula. 67 | ``` 68 | Maintainability Index = 171 - 5.2 * ln(Halstead Volume) - 0.23 * (Cyclomatic Complexity) - 16.2 * ln(Lines of Code) 69 | ``` 70 | 71 | This program shows normalized values instead of the original ones [introduced by Microsoft](https://docs.microsoft.com/en-us/archive/blogs/codeanalysis/maintainability-index-range-and-meaning). 72 | ``` 73 | Normalized Maintainability Index = MAX(0,(171 - 5.2 * ln(Halstead Volume) - 0.23 * (Cyclomatic Complexity) - 16.2 * ln(Lines of Code))*100 / 171) 74 | ``` 75 | 76 | The thresholds are as follows: 77 | ``` 78 | 0-9 = Red 79 | 10-19 = Yellow 80 | 20-100 = Green 81 | ``` 82 | 83 | 84 | -------------------------------------------------------------------------------- /cmd/complexity/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "github.com/rauzh/go-complexity-analysis" 5 | "golang.org/x/tools/go/analysis/unitchecker" 6 | ) 7 | 8 | func main() { 9 | unitchecker.Main(complexity.Analyzer) 10 | } 11 | -------------------------------------------------------------------------------- /complexity_test.go: -------------------------------------------------------------------------------- 1 | package complexity_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/rauzh/go-complexity-analysis" 7 | "golang.org/x/tools/go/analysis/analysistest" 8 | ) 9 | 10 | // TestAnalyzer is a test for Analyzer. 11 | func TestAnalyzer(t *testing.T) { 12 | testdata := analysistest.TestData() 13 | analysistest.Run(t, testdata, complexity.Analyzer, []string{"a", "halstead"}...) 14 | } 15 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/rauzh/go-complexity-analysis 2 | 3 | go 1.23.0 4 | 5 | require golang.org/x/tools v0.27.0 6 | 7 | require ( 8 | golang.org/x/mod v0.22.0 // indirect 9 | golang.org/x/sync v0.9.0 // indirect 10 | ) 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 2 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 3 | golang.org/x/mod v0.22.0 h1:D4nJWe9zXqHOmWqj4VMOJhvzj7bEZg4wEYa759z1pH4= 4 | golang.org/x/mod v0.22.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= 5 | golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ= 6 | golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= 7 | golang.org/x/tools v0.27.0 h1:qEKojBykQkQ4EynWy4S8Weg69NumxKdn40Fce3uc/8o= 8 | golang.org/x/tools v0.27.0/go.mod h1:sUi0ZgbwW9ZPAq26Ekut+weQPR5eIM6GQLQ1Yjm1H0Q= 9 | -------------------------------------------------------------------------------- /plugin/main.go: -------------------------------------------------------------------------------- 1 | // This file can build as a plugin for golangci-lint by below command. 2 | // go build -buildmode=plugin -o path_to_plugin_dir github.com/shoooooman/complexity/plugin/complexity 3 | // See: https://golangci-lint.run/contributing/new-linters/#how-to-add-a-private-linter-to-golangci-lint 4 | 5 | package main 6 | 7 | import ( 8 | "strings" 9 | 10 | "github.com/rauzh/go-complexity-analysis" 11 | "golang.org/x/tools/go/analysis" 12 | ) 13 | 14 | // flags for Analyzer.Flag. 15 | // If you would like to specify flags for your plugin, you can put them via 'ldflags' as below. 16 | // 17 | // $ go build -buildmode=plugin -ldflags "-X 'main.flags=-opt val'" github.com/shoooooman/complexity/plugin/complexity 18 | var flags string 19 | 20 | // AnalyzerPlugin provides analyzers as a plugin. 21 | // It follows golangci-lint style plugin. 22 | var AnalyzerPlugin analyzerPlugin 23 | 24 | type analyzerPlugin struct{} 25 | 26 | func (analyzerPlugin) GetAnalyzers() []*analysis.Analyzer { 27 | if flags != "" { 28 | flagset := complexity.Analyzer.Flags 29 | if err := flagset.Parse(strings.Split(flags, " ")); err != nil { 30 | panic("cannot parse flags of complexity: " + err.Error()) 31 | } 32 | } 33 | return []*analysis.Analyzer{ 34 | complexity.Analyzer, 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /testdata/src/a/a.go: -------------------------------------------------------------------------------- 1 | package a 2 | 3 | func f0() { // want "Cyclomatic complexity: 1" 4 | } 5 | 6 | func f1() { // want "Cyclomatic complexity: 2" 7 | if false { 8 | 9 | } else { 10 | 11 | } 12 | } 13 | 14 | func f2() { // want "Cyclomatic complexity: 9" 15 | for true { 16 | if false { 17 | 18 | } else if false { 19 | 20 | } else if false { 21 | 22 | } else if false { 23 | n := 0 24 | switch n { 25 | case 0: 26 | case 1: 27 | default: 28 | } 29 | } else { 30 | 31 | } 32 | } 33 | } 34 | 35 | func f3() { // want "Cyclomatic complexity: 4" 36 | if false || true { 37 | if false { 38 | 39 | } 40 | } 41 | } 42 | 43 | func f4() { // want "Cyclomatic complexity: 11" 44 | n := 0 45 | switch n { 46 | case 0: 47 | case 1: 48 | case 2: 49 | case 3: 50 | case 4: 51 | case 5: 52 | case 6: 53 | case 7: 54 | case 8: 55 | case 9: 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /testdata/src/halstead/a.go: -------------------------------------------------------------------------------- 1 | package halstead 2 | 3 | func f1() { // want "Cyclomatic complexity: 1, Halstead difficulty: 2.500, volume: 18.095" 4 | print("Hello, World") 5 | } 6 | 7 | func f2() { // want "Cyclomatic complexity: 1, Halstead difficulty: 6.857, volume: 101.579" 8 | a := 2 9 | b := 1 10 | c := 3 11 | avg := (a + b + c) / 3 12 | println(avg) 13 | } 14 | 15 | func f3() { // want "Cyclomatic complexity: 2, Halstead difficulty: NaN, volume: 25.266" 16 | if false { 17 | 18 | } else { 19 | 20 | } 21 | } 22 | 23 | func f4() { // want "Cyclomatic complexity: 9, Halstead difficulty: 10.833, volume: 144.000" 24 | for true { 25 | if false { 26 | 27 | } else if false { 28 | 29 | } else if false { 30 | 31 | } else if false { 32 | n := 0 33 | switch n { 34 | case 0: 35 | case 1: 36 | default: 37 | } 38 | } else { 39 | 40 | } 41 | } 42 | } 43 | 44 | type t1 struct { 45 | } 46 | 47 | func (t *t1) f5() { // want "Cyclomatic complexity: 1, Halstead difficulty: NaN, volume: 10.000" 48 | } 49 | -------------------------------------------------------------------------------- /testdata/src/halstead/b.go: -------------------------------------------------------------------------------- 1 | package halstead 2 | 3 | import "fmt" 4 | 5 | func comp1() { // want "Cyclomatic complexity: 1, Halstead difficulty: 7.000, volume: 38.039" 6 | var a int 7 | a++ 8 | print(a) 9 | } 10 | 11 | func comp2() { // want "Cyclomatic complexity: 1, Halstead difficulty: 3.500, volume: 41.209" 12 | defer fmt.Println("world") 13 | 14 | fmt.Println("hello") 15 | } 16 | 17 | func comp3() { // want "Cyclomatic complexity: 1, Halstead difficulty: 3.500, volume: 41.209" 18 | go fmt.Println("hello") 19 | fmt.Println("world") 20 | } 21 | 22 | func comp4() { // want "Cyclomatic complexity: 1, Halstead difficulty: 12.000, volume: 101.579" 23 | a := make(chan string) 24 | go func() { a <- "ping" }() 25 | 26 | b := <-a 27 | fmt.Println(b) 28 | } 29 | 30 | func comp5() { // want "Cyclomatic complexity: 1, Halstead difficulty: 3.500, volume: 27.000" 31 | fmt.Println("Hello, 世界!") 32 | return 33 | } 34 | 35 | func comp6() { // want "Cyclomatic complexity: 3, Halstead difficulty: 7.500, volume: 92.000" 36 | var a int 37 | for a < 5 { 38 | if a < 3 { 39 | continue 40 | } else { 41 | break 42 | } 43 | a++ 44 | } 45 | } 46 | 47 | func comp7() { // want "Cyclomatic complexity: 3, Halstead difficulty: 9.000, volume: 88.000" 48 | c1 := make(chan string) 49 | 50 | for i := 0; i < 2; i++ { 51 | select { 52 | case msg1 := <-c1: 53 | fmt.Println("received", msg1) 54 | } 55 | } 56 | } 57 | func comp8() { // want "Cyclomatic complexity: 2, Halstead difficulty: 6.300, volume: 76.147" 58 | a := []int{0, 1, 2} 59 | for b := range a { 60 | fmt.Println(b) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /vendor/golang.org/x/mod/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2009 The Go Authors. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google LLC nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/mod/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/mod/internal/lazyregexp/lazyre.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package lazyregexp is a thin wrapper over regexp, allowing the use of global 6 | // regexp variables without forcing them to be compiled at init. 7 | package lazyregexp 8 | 9 | import ( 10 | "os" 11 | "regexp" 12 | "strings" 13 | "sync" 14 | ) 15 | 16 | // Regexp is a wrapper around [regexp.Regexp], where the underlying regexp will be 17 | // compiled the first time it is needed. 18 | type Regexp struct { 19 | str string 20 | once sync.Once 21 | rx *regexp.Regexp 22 | } 23 | 24 | func (r *Regexp) re() *regexp.Regexp { 25 | r.once.Do(r.build) 26 | return r.rx 27 | } 28 | 29 | func (r *Regexp) build() { 30 | r.rx = regexp.MustCompile(r.str) 31 | r.str = "" 32 | } 33 | 34 | func (r *Regexp) FindSubmatch(s []byte) [][]byte { 35 | return r.re().FindSubmatch(s) 36 | } 37 | 38 | func (r *Regexp) FindStringSubmatch(s string) []string { 39 | return r.re().FindStringSubmatch(s) 40 | } 41 | 42 | func (r *Regexp) FindStringSubmatchIndex(s string) []int { 43 | return r.re().FindStringSubmatchIndex(s) 44 | } 45 | 46 | func (r *Regexp) ReplaceAllString(src, repl string) string { 47 | return r.re().ReplaceAllString(src, repl) 48 | } 49 | 50 | func (r *Regexp) FindString(s string) string { 51 | return r.re().FindString(s) 52 | } 53 | 54 | func (r *Regexp) FindAllString(s string, n int) []string { 55 | return r.re().FindAllString(s, n) 56 | } 57 | 58 | func (r *Regexp) MatchString(s string) bool { 59 | return r.re().MatchString(s) 60 | } 61 | 62 | func (r *Regexp) SubexpNames() []string { 63 | return r.re().SubexpNames() 64 | } 65 | 66 | var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") 67 | 68 | // New creates a new lazy regexp, delaying the compiling work until it is first 69 | // needed. If the code is being run as part of tests, the regexp compiling will 70 | // happen immediately. 71 | func New(str string) *Regexp { 72 | lr := &Regexp{str: str} 73 | if inTest { 74 | // In tests, always compile the regexps early. 75 | lr.re() 76 | } 77 | return lr 78 | } 79 | -------------------------------------------------------------------------------- /vendor/golang.org/x/mod/modfile/print.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Module file printer. 6 | 7 | package modfile 8 | 9 | import ( 10 | "bytes" 11 | "fmt" 12 | "strings" 13 | ) 14 | 15 | // Format returns a go.mod file as a byte slice, formatted in standard style. 16 | func Format(f *FileSyntax) []byte { 17 | pr := &printer{} 18 | pr.file(f) 19 | 20 | // remove trailing blank lines 21 | b := pr.Bytes() 22 | for len(b) > 0 && b[len(b)-1] == '\n' && (len(b) == 1 || b[len(b)-2] == '\n') { 23 | b = b[:len(b)-1] 24 | } 25 | return b 26 | } 27 | 28 | // A printer collects the state during printing of a file or expression. 29 | type printer struct { 30 | bytes.Buffer // output buffer 31 | comment []Comment // pending end-of-line comments 32 | margin int // left margin (indent), a number of tabs 33 | } 34 | 35 | // printf prints to the buffer. 36 | func (p *printer) printf(format string, args ...interface{}) { 37 | fmt.Fprintf(p, format, args...) 38 | } 39 | 40 | // indent returns the position on the current line, in bytes, 0-indexed. 41 | func (p *printer) indent() int { 42 | b := p.Bytes() 43 | n := 0 44 | for n < len(b) && b[len(b)-1-n] != '\n' { 45 | n++ 46 | } 47 | return n 48 | } 49 | 50 | // newline ends the current line, flushing end-of-line comments. 51 | func (p *printer) newline() { 52 | if len(p.comment) > 0 { 53 | p.printf(" ") 54 | for i, com := range p.comment { 55 | if i > 0 { 56 | p.trim() 57 | p.printf("\n") 58 | for i := 0; i < p.margin; i++ { 59 | p.printf("\t") 60 | } 61 | } 62 | p.printf("%s", strings.TrimSpace(com.Token)) 63 | } 64 | p.comment = p.comment[:0] 65 | } 66 | 67 | p.trim() 68 | if b := p.Bytes(); len(b) == 0 || (len(b) >= 2 && b[len(b)-1] == '\n' && b[len(b)-2] == '\n') { 69 | // skip the blank line at top of file or after a blank line 70 | } else { 71 | p.printf("\n") 72 | } 73 | for i := 0; i < p.margin; i++ { 74 | p.printf("\t") 75 | } 76 | } 77 | 78 | // trim removes trailing spaces and tabs from the current line. 79 | func (p *printer) trim() { 80 | // Remove trailing spaces and tabs from line we're about to end. 81 | b := p.Bytes() 82 | n := len(b) 83 | for n > 0 && (b[n-1] == '\t' || b[n-1] == ' ') { 84 | n-- 85 | } 86 | p.Truncate(n) 87 | } 88 | 89 | // file formats the given file into the print buffer. 90 | func (p *printer) file(f *FileSyntax) { 91 | for _, com := range f.Before { 92 | p.printf("%s", strings.TrimSpace(com.Token)) 93 | p.newline() 94 | } 95 | 96 | for i, stmt := range f.Stmt { 97 | switch x := stmt.(type) { 98 | case *CommentBlock: 99 | // comments already handled 100 | p.expr(x) 101 | 102 | default: 103 | p.expr(x) 104 | p.newline() 105 | } 106 | 107 | for _, com := range stmt.Comment().After { 108 | p.printf("%s", strings.TrimSpace(com.Token)) 109 | p.newline() 110 | } 111 | 112 | if i+1 < len(f.Stmt) { 113 | p.newline() 114 | } 115 | } 116 | } 117 | 118 | func (p *printer) expr(x Expr) { 119 | // Emit line-comments preceding this expression. 120 | if before := x.Comment().Before; len(before) > 0 { 121 | // Want to print a line comment. 122 | // Line comments must be at the current margin. 123 | p.trim() 124 | if p.indent() > 0 { 125 | // There's other text on the line. Start a new line. 126 | p.printf("\n") 127 | } 128 | // Re-indent to margin. 129 | for i := 0; i < p.margin; i++ { 130 | p.printf("\t") 131 | } 132 | for _, com := range before { 133 | p.printf("%s", strings.TrimSpace(com.Token)) 134 | p.newline() 135 | } 136 | } 137 | 138 | switch x := x.(type) { 139 | default: 140 | panic(fmt.Errorf("printer: unexpected type %T", x)) 141 | 142 | case *CommentBlock: 143 | // done 144 | 145 | case *LParen: 146 | p.printf("(") 147 | case *RParen: 148 | p.printf(")") 149 | 150 | case *Line: 151 | p.tokens(x.Token) 152 | 153 | case *LineBlock: 154 | p.tokens(x.Token) 155 | p.printf(" ") 156 | p.expr(&x.LParen) 157 | p.margin++ 158 | for _, l := range x.Line { 159 | p.newline() 160 | p.expr(l) 161 | } 162 | p.margin-- 163 | p.newline() 164 | p.expr(&x.RParen) 165 | } 166 | 167 | // Queue end-of-line comments for printing when we 168 | // reach the end of the line. 169 | p.comment = append(p.comment, x.Comment().Suffix...) 170 | } 171 | 172 | func (p *printer) tokens(tokens []string) { 173 | sep := "" 174 | for _, t := range tokens { 175 | if t == "," || t == ")" || t == "]" || t == "}" { 176 | sep = "" 177 | } 178 | p.printf("%s%s", sep, t) 179 | sep = " " 180 | if t == "(" || t == "[" || t == "{" { 181 | sep = "" 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sync/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2009 The Go Authors. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google LLC nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sync/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sync/errgroup/errgroup.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package errgroup provides synchronization, error propagation, and Context 6 | // cancelation for groups of goroutines working on subtasks of a common task. 7 | // 8 | // [errgroup.Group] is related to [sync.WaitGroup] but adds handling of tasks 9 | // returning errors. 10 | package errgroup 11 | 12 | import ( 13 | "context" 14 | "fmt" 15 | "sync" 16 | ) 17 | 18 | type token struct{} 19 | 20 | // A Group is a collection of goroutines working on subtasks that are part of 21 | // the same overall task. 22 | // 23 | // A zero Group is valid, has no limit on the number of active goroutines, 24 | // and does not cancel on error. 25 | type Group struct { 26 | cancel func(error) 27 | 28 | wg sync.WaitGroup 29 | 30 | sem chan token 31 | 32 | errOnce sync.Once 33 | err error 34 | } 35 | 36 | func (g *Group) done() { 37 | if g.sem != nil { 38 | <-g.sem 39 | } 40 | g.wg.Done() 41 | } 42 | 43 | // WithContext returns a new Group and an associated Context derived from ctx. 44 | // 45 | // The derived Context is canceled the first time a function passed to Go 46 | // returns a non-nil error or the first time Wait returns, whichever occurs 47 | // first. 48 | func WithContext(ctx context.Context) (*Group, context.Context) { 49 | ctx, cancel := withCancelCause(ctx) 50 | return &Group{cancel: cancel}, ctx 51 | } 52 | 53 | // Wait blocks until all function calls from the Go method have returned, then 54 | // returns the first non-nil error (if any) from them. 55 | func (g *Group) Wait() error { 56 | g.wg.Wait() 57 | if g.cancel != nil { 58 | g.cancel(g.err) 59 | } 60 | return g.err 61 | } 62 | 63 | // Go calls the given function in a new goroutine. 64 | // It blocks until the new goroutine can be added without the number of 65 | // active goroutines in the group exceeding the configured limit. 66 | // 67 | // The first call to return a non-nil error cancels the group's context, if the 68 | // group was created by calling WithContext. The error will be returned by Wait. 69 | func (g *Group) Go(f func() error) { 70 | if g.sem != nil { 71 | g.sem <- token{} 72 | } 73 | 74 | g.wg.Add(1) 75 | go func() { 76 | defer g.done() 77 | 78 | if err := f(); err != nil { 79 | g.errOnce.Do(func() { 80 | g.err = err 81 | if g.cancel != nil { 82 | g.cancel(g.err) 83 | } 84 | }) 85 | } 86 | }() 87 | } 88 | 89 | // TryGo calls the given function in a new goroutine only if the number of 90 | // active goroutines in the group is currently below the configured limit. 91 | // 92 | // The return value reports whether the goroutine was started. 93 | func (g *Group) TryGo(f func() error) bool { 94 | if g.sem != nil { 95 | select { 96 | case g.sem <- token{}: 97 | // Note: this allows barging iff channels in general allow barging. 98 | default: 99 | return false 100 | } 101 | } 102 | 103 | g.wg.Add(1) 104 | go func() { 105 | defer g.done() 106 | 107 | if err := f(); err != nil { 108 | g.errOnce.Do(func() { 109 | g.err = err 110 | if g.cancel != nil { 111 | g.cancel(g.err) 112 | } 113 | }) 114 | } 115 | }() 116 | return true 117 | } 118 | 119 | // SetLimit limits the number of active goroutines in this group to at most n. 120 | // A negative value indicates no limit. 121 | // 122 | // Any subsequent call to the Go method will block until it can add an active 123 | // goroutine without exceeding the configured limit. 124 | // 125 | // The limit must not be modified while any goroutines in the group are active. 126 | func (g *Group) SetLimit(n int) { 127 | if n < 0 { 128 | g.sem = nil 129 | return 130 | } 131 | if len(g.sem) != 0 { 132 | panic(fmt.Errorf("errgroup: modify limit while %v goroutines in the group are still active", len(g.sem))) 133 | } 134 | g.sem = make(chan token, n) 135 | } 136 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sync/errgroup/go120.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build go1.20 6 | 7 | package errgroup 8 | 9 | import "context" 10 | 11 | func withCancelCause(parent context.Context) (context.Context, func(error)) { 12 | return context.WithCancelCause(parent) 13 | } 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/sync/errgroup/pre_go120.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build !go1.20 6 | 7 | package errgroup 8 | 9 | import "context" 10 | 11 | func withCancelCause(parent context.Context) (context.Context, func(error)) { 12 | ctx, cancel := context.WithCancel(parent) 13 | return ctx, func(error) { cancel() } 14 | } 15 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2009 The Go Authors. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google LLC nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/PATENTS: -------------------------------------------------------------------------------- 1 | Additional IP Rights Grant (Patents) 2 | 3 | "This implementation" means the copyrightable works distributed by 4 | Google as part of the Go project. 5 | 6 | Google hereby grants to You a perpetual, worldwide, non-exclusive, 7 | no-charge, royalty-free, irrevocable (except as stated in this section) 8 | patent license to make, have made, use, offer to sell, sell, import, 9 | transfer and otherwise run, modify and propagate the contents of this 10 | implementation of Go, where such license applies only to those patent 11 | claims, both currently owned or controlled by Google and acquired in 12 | the future, licensable by Google that are necessarily infringed by this 13 | implementation of Go. This grant does not include claims that would be 14 | infringed only as a consequence of further modification of this 15 | implementation. If you or your agent or exclusive licensee institute or 16 | order or agree to the institution of patent litigation against any 17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging 18 | that this implementation of Go or any code incorporated within this 19 | implementation of Go constitutes direct or contributory patent 20 | infringement, or inducement of patent infringement, then any patent 21 | rights granted to you under this License for this implementation of Go 22 | shall terminate as of the date such litigation is filed. 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/analysis/diagnostic.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package analysis 6 | 7 | import "go/token" 8 | 9 | // A Diagnostic is a message associated with a source location or range. 10 | // 11 | // An Analyzer may return a variety of diagnostics; the optional Category, 12 | // which should be a constant, may be used to classify them. 13 | // It is primarily intended to make it easy to look up documentation. 14 | // 15 | // All Pos values are interpreted relative to Pass.Fset. If End is 16 | // provided, the diagnostic is specified to apply to the range between 17 | // Pos and End. 18 | type Diagnostic struct { 19 | Pos token.Pos 20 | End token.Pos // optional 21 | Category string // optional 22 | Message string 23 | 24 | // URL is the optional location of a web page that provides 25 | // additional documentation for this diagnostic. 26 | // 27 | // If URL is empty but a Category is specified, then the 28 | // Analysis driver should treat the URL as "#"+Category. 29 | // 30 | // The URL may be relative. If so, the base URL is that of the 31 | // Analyzer that produced the diagnostic; 32 | // see https://pkg.go.dev/net/url#URL.ResolveReference. 33 | URL string 34 | 35 | // SuggestedFixes is an optional list of fixes to address the 36 | // problem described by the diagnostic. Each one represents 37 | // an alternative strategy; at most one may be applied. 38 | // 39 | // Fixes for different diagnostics should be treated as 40 | // independent changes to the same baseline file state, 41 | // analogous to a set of git commits all with the same parent. 42 | // Combining fixes requires resolving any conflicts that 43 | // arise, analogous to a git merge. 44 | // Any conflicts that remain may be dealt with, depending on 45 | // the tool, by discarding fixes, consulting the user, or 46 | // aborting the operation. 47 | SuggestedFixes []SuggestedFix 48 | 49 | // Related contains optional secondary positions and messages 50 | // related to the primary diagnostic. 51 | Related []RelatedInformation 52 | } 53 | 54 | // RelatedInformation contains information related to a diagnostic. 55 | // For example, a diagnostic that flags duplicated declarations of a 56 | // variable may include one RelatedInformation per existing 57 | // declaration. 58 | type RelatedInformation struct { 59 | Pos token.Pos 60 | End token.Pos // optional 61 | Message string 62 | } 63 | 64 | // A SuggestedFix is a code change associated with a Diagnostic that a 65 | // user can choose to apply to their code. Usually the SuggestedFix is 66 | // meant to fix the issue flagged by the diagnostic. 67 | // 68 | // The TextEdits must not overlap, nor contain edits for other packages. 69 | type SuggestedFix struct { 70 | // A verb phrase describing the fix, to be shown to 71 | // a user trying to decide whether to accept it. 72 | // 73 | // Example: "Remove the surplus argument" 74 | Message string 75 | TextEdits []TextEdit 76 | } 77 | 78 | // A TextEdit represents the replacement of the code between Pos and End with the new text. 79 | // Each TextEdit should apply to a single file. End should not be earlier in the file than Pos. 80 | type TextEdit struct { 81 | // For a pure insertion, End can either be set to Pos or token.NoPos. 82 | Pos token.Pos 83 | End token.Pos 84 | NewText []byte 85 | } 86 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/analysis/internal/analysisflags/help.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package analysisflags 6 | 7 | import ( 8 | "flag" 9 | "fmt" 10 | "log" 11 | "os" 12 | "sort" 13 | "strings" 14 | 15 | "golang.org/x/tools/go/analysis" 16 | ) 17 | 18 | const help = `PROGNAME is a tool for static analysis of Go programs. 19 | 20 | PROGNAME examines Go source code and reports suspicious constructs, 21 | such as Printf calls whose arguments do not align with the format 22 | string. It uses heuristics that do not guarantee all reports are 23 | genuine problems, but it can find errors not caught by the compilers. 24 | ` 25 | 26 | // Help implements the help subcommand for a multichecker or unitchecker 27 | // style command. The optional args specify the analyzers to describe. 28 | // Help calls log.Fatal if no such analyzer exists. 29 | func Help(progname string, analyzers []*analysis.Analyzer, args []string) { 30 | // No args: show summary of all analyzers. 31 | if len(args) == 0 { 32 | fmt.Println(strings.Replace(help, "PROGNAME", progname, -1)) 33 | fmt.Println("Registered analyzers:") 34 | fmt.Println() 35 | sort.Slice(analyzers, func(i, j int) bool { 36 | return analyzers[i].Name < analyzers[j].Name 37 | }) 38 | for _, a := range analyzers { 39 | title := strings.Split(a.Doc, "\n\n")[0] 40 | fmt.Printf(" %-12s %s\n", a.Name, title) 41 | } 42 | fmt.Println("\nBy default all analyzers are run.") 43 | fmt.Println("To select specific analyzers, use the -NAME flag for each one,") 44 | fmt.Println(" or -NAME=false to run all analyzers not explicitly disabled.") 45 | 46 | // Show only the core command-line flags. 47 | fmt.Println("\nCore flags:") 48 | fmt.Println() 49 | fs := flag.NewFlagSet("", flag.ExitOnError) 50 | flag.VisitAll(func(f *flag.Flag) { 51 | if !strings.Contains(f.Name, ".") { 52 | fs.Var(f.Value, f.Name, f.Usage) 53 | } 54 | }) 55 | fs.SetOutput(os.Stdout) 56 | fs.PrintDefaults() 57 | 58 | fmt.Printf("\nTo see details and flags of a specific analyzer, run '%s help name'.\n", progname) 59 | 60 | return 61 | } 62 | 63 | // Show help on specific analyzer(s). 64 | outer: 65 | for _, arg := range args { 66 | for _, a := range analyzers { 67 | if a.Name == arg { 68 | paras := strings.Split(a.Doc, "\n\n") 69 | title := paras[0] 70 | fmt.Printf("%s: %s\n", a.Name, title) 71 | 72 | // Show only the flags relating to this analysis, 73 | // properly prefixed. 74 | first := true 75 | fs := flag.NewFlagSet(a.Name, flag.ExitOnError) 76 | a.Flags.VisitAll(func(f *flag.Flag) { 77 | if first { 78 | first = false 79 | fmt.Println("\nAnalyzer flags:") 80 | fmt.Println() 81 | } 82 | fs.Var(f.Value, a.Name+"."+f.Name, f.Usage) 83 | }) 84 | fs.SetOutput(os.Stdout) 85 | fs.PrintDefaults() 86 | 87 | if len(paras) > 1 { 88 | fmt.Printf("\n%s\n", strings.Join(paras[1:], "\n\n")) 89 | } 90 | 91 | continue outer 92 | } 93 | } 94 | log.Fatalf("Analyzer %q not registered", arg) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/analysis/internal/analysisflags/url.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package analysisflags 6 | 7 | import ( 8 | "fmt" 9 | "net/url" 10 | 11 | "golang.org/x/tools/go/analysis" 12 | ) 13 | 14 | // ResolveURL resolves the URL field for a Diagnostic from an Analyzer 15 | // and returns the URL. See Diagnostic.URL for details. 16 | func ResolveURL(a *analysis.Analyzer, d analysis.Diagnostic) (string, error) { 17 | if d.URL == "" && d.Category == "" && a.URL == "" { 18 | return "", nil // do nothing 19 | } 20 | raw := d.URL 21 | if d.URL == "" && d.Category != "" { 22 | raw = "#" + d.Category 23 | } 24 | u, err := url.Parse(raw) 25 | if err != nil { 26 | return "", fmt.Errorf("invalid Diagnostic.URL %q: %s", raw, err) 27 | } 28 | base, err := url.Parse(a.URL) 29 | if err != nil { 30 | return "", fmt.Errorf("invalid Analyzer.URL %q: %s", a.URL, err) 31 | } 32 | return base.ResolveReference(u).String(), nil 33 | } 34 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/analysis/passes/inspect/inspect.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package inspect defines an Analyzer that provides an AST inspector 6 | // (golang.org/x/tools/go/ast/inspector.Inspector) for the syntax trees 7 | // of a package. It is only a building block for other analyzers. 8 | // 9 | // Example of use in another analysis: 10 | // 11 | // import ( 12 | // "golang.org/x/tools/go/analysis" 13 | // "golang.org/x/tools/go/analysis/passes/inspect" 14 | // "golang.org/x/tools/go/ast/inspector" 15 | // ) 16 | // 17 | // var Analyzer = &analysis.Analyzer{ 18 | // ... 19 | // Requires: []*analysis.Analyzer{inspect.Analyzer}, 20 | // } 21 | // 22 | // func run(pass *analysis.Pass) (interface{}, error) { 23 | // inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) 24 | // inspect.Preorder(nil, func(n ast.Node) { 25 | // ... 26 | // }) 27 | // return nil, nil 28 | // } 29 | package inspect 30 | 31 | import ( 32 | "reflect" 33 | 34 | "golang.org/x/tools/go/analysis" 35 | "golang.org/x/tools/go/ast/inspector" 36 | ) 37 | 38 | var Analyzer = &analysis.Analyzer{ 39 | Name: "inspect", 40 | Doc: "optimize AST traversal for later passes", 41 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/inspect", 42 | Run: run, 43 | RunDespiteErrors: true, 44 | ResultType: reflect.TypeOf(new(inspector.Inspector)), 45 | } 46 | 47 | func run(pass *analysis.Pass) (interface{}, error) { 48 | return inspector.New(pass.Files), nil 49 | } 50 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/analysis/validate.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package analysis 6 | 7 | import ( 8 | "fmt" 9 | "reflect" 10 | "strings" 11 | "unicode" 12 | ) 13 | 14 | // Validate reports an error if any of the analyzers are misconfigured. 15 | // Checks include: 16 | // that the name is a valid identifier; 17 | // that the Doc is not empty; 18 | // that the Run is non-nil; 19 | // that the Requires graph is acyclic; 20 | // that analyzer fact types are unique; 21 | // that each fact type is a pointer. 22 | // 23 | // Analyzer names need not be unique, though this may be confusing. 24 | func Validate(analyzers []*Analyzer) error { 25 | // Map each fact type to its sole generating analyzer. 26 | factTypes := make(map[reflect.Type]*Analyzer) 27 | 28 | // Traverse the Requires graph, depth first. 29 | const ( 30 | white = iota 31 | grey 32 | black 33 | finished 34 | ) 35 | color := make(map[*Analyzer]uint8) 36 | var visit func(a *Analyzer) error 37 | visit = func(a *Analyzer) error { 38 | if a == nil { 39 | return fmt.Errorf("nil *Analyzer") 40 | } 41 | if color[a] == white { 42 | color[a] = grey 43 | 44 | // names 45 | if !validIdent(a.Name) { 46 | return fmt.Errorf("invalid analyzer name %q", a) 47 | } 48 | 49 | if a.Doc == "" { 50 | return fmt.Errorf("analyzer %q is undocumented", a) 51 | } 52 | 53 | if a.Run == nil { 54 | return fmt.Errorf("analyzer %q has nil Run", a) 55 | } 56 | // fact types 57 | for _, f := range a.FactTypes { 58 | if f == nil { 59 | return fmt.Errorf("analyzer %s has nil FactType", a) 60 | } 61 | t := reflect.TypeOf(f) 62 | if prev := factTypes[t]; prev != nil { 63 | return fmt.Errorf("fact type %s registered by two analyzers: %v, %v", 64 | t, a, prev) 65 | } 66 | if t.Kind() != reflect.Ptr { 67 | return fmt.Errorf("%s: fact type %s is not a pointer", a, t) 68 | } 69 | factTypes[t] = a 70 | } 71 | 72 | // recursion 73 | for _, req := range a.Requires { 74 | if err := visit(req); err != nil { 75 | return err 76 | } 77 | } 78 | color[a] = black 79 | } 80 | 81 | if color[a] == grey { 82 | stack := []*Analyzer{a} 83 | inCycle := map[string]bool{} 84 | for len(stack) > 0 { 85 | current := stack[len(stack)-1] 86 | stack = stack[:len(stack)-1] 87 | if color[current] == grey && !inCycle[current.Name] { 88 | inCycle[current.Name] = true 89 | stack = append(stack, current.Requires...) 90 | } 91 | } 92 | return &CycleInRequiresGraphError{AnalyzerNames: inCycle} 93 | } 94 | 95 | return nil 96 | } 97 | for _, a := range analyzers { 98 | if err := visit(a); err != nil { 99 | return err 100 | } 101 | } 102 | 103 | // Reject duplicates among analyzers. 104 | // Precondition: color[a] == black. 105 | // Postcondition: color[a] == finished. 106 | for _, a := range analyzers { 107 | if color[a] == finished { 108 | return fmt.Errorf("duplicate analyzer: %s", a.Name) 109 | } 110 | color[a] = finished 111 | } 112 | 113 | return nil 114 | } 115 | 116 | func validIdent(name string) bool { 117 | for i, r := range name { 118 | if !(r == '_' || unicode.IsLetter(r) || i > 0 && unicode.IsDigit(r)) { 119 | return false 120 | } 121 | } 122 | return name != "" 123 | } 124 | 125 | type CycleInRequiresGraphError struct { 126 | AnalyzerNames map[string]bool 127 | } 128 | 129 | func (e *CycleInRequiresGraphError) Error() string { 130 | var b strings.Builder 131 | b.WriteString("cycle detected involving the following analyzers:") 132 | for n := range e.AnalyzerNames { 133 | b.WriteByte(' ') 134 | b.WriteString(n) 135 | } 136 | return b.String() 137 | } 138 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/ast/inspector/iter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build go1.23 6 | 7 | package inspector 8 | 9 | import ( 10 | "go/ast" 11 | "iter" 12 | ) 13 | 14 | // PreorderSeq returns an iterator that visits all the 15 | // nodes of the files supplied to New in depth-first order. 16 | // It visits each node n before n's children. 17 | // The complete traversal sequence is determined by ast.Inspect. 18 | // 19 | // The types argument, if non-empty, enables type-based 20 | // filtering of events: only nodes whose type matches an 21 | // element of the types slice are included in the sequence. 22 | func (in *Inspector) PreorderSeq(types ...ast.Node) iter.Seq[ast.Node] { 23 | 24 | // This implementation is identical to Preorder, 25 | // except that it supports breaking out of the loop. 26 | 27 | return func(yield func(ast.Node) bool) { 28 | mask := maskOf(types) 29 | for i := 0; i < len(in.events); { 30 | ev := in.events[i] 31 | if ev.index > i { 32 | // push 33 | if ev.typ&mask != 0 { 34 | if !yield(ev.node) { 35 | break 36 | } 37 | } 38 | pop := ev.index 39 | if in.events[pop].typ&mask == 0 { 40 | // Subtrees do not contain types: skip them and pop. 41 | i = pop + 1 42 | continue 43 | } 44 | } 45 | i++ 46 | } 47 | } 48 | } 49 | 50 | // All[N] returns an iterator over all the nodes of type N. 51 | // N must be a pointer-to-struct type that implements ast.Node. 52 | // 53 | // Example: 54 | // 55 | // for call := range All[*ast.CallExpr](in) { ... } 56 | func All[N interface { 57 | *S 58 | ast.Node 59 | }, S any](in *Inspector) iter.Seq[N] { 60 | 61 | // To avoid additional dynamic call overheads, 62 | // we duplicate rather than call the logic of PreorderSeq. 63 | 64 | mask := typeOf((N)(nil)) 65 | return func(yield func(N) bool) { 66 | for i := 0; i < len(in.events); { 67 | ev := in.events[i] 68 | if ev.index > i { 69 | // push 70 | if ev.typ&mask != 0 { 71 | if !yield(ev.node.(N)) { 72 | break 73 | } 74 | } 75 | pop := ev.index 76 | if in.events[pop].typ&mask == 0 { 77 | // Subtrees do not contain types: skip them and pop. 78 | i = pop + 1 79 | continue 80 | } 81 | } 82 | i++ 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/ast/inspector/typeof.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package inspector 6 | 7 | // This file defines func typeOf(ast.Node) uint64. 8 | // 9 | // The initial map-based implementation was too slow; 10 | // see https://go-review.googlesource.com/c/tools/+/135655/1/go/ast/inspector/inspector.go#196 11 | 12 | import ( 13 | "go/ast" 14 | "math" 15 | ) 16 | 17 | const ( 18 | nArrayType = iota 19 | nAssignStmt 20 | nBadDecl 21 | nBadExpr 22 | nBadStmt 23 | nBasicLit 24 | nBinaryExpr 25 | nBlockStmt 26 | nBranchStmt 27 | nCallExpr 28 | nCaseClause 29 | nChanType 30 | nCommClause 31 | nComment 32 | nCommentGroup 33 | nCompositeLit 34 | nDeclStmt 35 | nDeferStmt 36 | nEllipsis 37 | nEmptyStmt 38 | nExprStmt 39 | nField 40 | nFieldList 41 | nFile 42 | nForStmt 43 | nFuncDecl 44 | nFuncLit 45 | nFuncType 46 | nGenDecl 47 | nGoStmt 48 | nIdent 49 | nIfStmt 50 | nImportSpec 51 | nIncDecStmt 52 | nIndexExpr 53 | nIndexListExpr 54 | nInterfaceType 55 | nKeyValueExpr 56 | nLabeledStmt 57 | nMapType 58 | nPackage 59 | nParenExpr 60 | nRangeStmt 61 | nReturnStmt 62 | nSelectStmt 63 | nSelectorExpr 64 | nSendStmt 65 | nSliceExpr 66 | nStarExpr 67 | nStructType 68 | nSwitchStmt 69 | nTypeAssertExpr 70 | nTypeSpec 71 | nTypeSwitchStmt 72 | nUnaryExpr 73 | nValueSpec 74 | ) 75 | 76 | // typeOf returns a distinct single-bit value that represents the type of n. 77 | // 78 | // Various implementations were benchmarked with BenchmarkNewInspector: 79 | // 80 | // GOGC=off 81 | // - type switch 4.9-5.5ms 2.1ms 82 | // - binary search over a sorted list of types 5.5-5.9ms 2.5ms 83 | // - linear scan, frequency-ordered list 5.9-6.1ms 2.7ms 84 | // - linear scan, unordered list 6.4ms 2.7ms 85 | // - hash table 6.5ms 3.1ms 86 | // 87 | // A perfect hash seemed like overkill. 88 | // 89 | // The compiler's switch statement is the clear winner 90 | // as it produces a binary tree in code, 91 | // with constant conditions and good branch prediction. 92 | // (Sadly it is the most verbose in source code.) 93 | // Binary search suffered from poor branch prediction. 94 | func typeOf(n ast.Node) uint64 { 95 | // Fast path: nearly half of all nodes are identifiers. 96 | if _, ok := n.(*ast.Ident); ok { 97 | return 1 << nIdent 98 | } 99 | 100 | // These cases include all nodes encountered by ast.Inspect. 101 | switch n.(type) { 102 | case *ast.ArrayType: 103 | return 1 << nArrayType 104 | case *ast.AssignStmt: 105 | return 1 << nAssignStmt 106 | case *ast.BadDecl: 107 | return 1 << nBadDecl 108 | case *ast.BadExpr: 109 | return 1 << nBadExpr 110 | case *ast.BadStmt: 111 | return 1 << nBadStmt 112 | case *ast.BasicLit: 113 | return 1 << nBasicLit 114 | case *ast.BinaryExpr: 115 | return 1 << nBinaryExpr 116 | case *ast.BlockStmt: 117 | return 1 << nBlockStmt 118 | case *ast.BranchStmt: 119 | return 1 << nBranchStmt 120 | case *ast.CallExpr: 121 | return 1 << nCallExpr 122 | case *ast.CaseClause: 123 | return 1 << nCaseClause 124 | case *ast.ChanType: 125 | return 1 << nChanType 126 | case *ast.CommClause: 127 | return 1 << nCommClause 128 | case *ast.Comment: 129 | return 1 << nComment 130 | case *ast.CommentGroup: 131 | return 1 << nCommentGroup 132 | case *ast.CompositeLit: 133 | return 1 << nCompositeLit 134 | case *ast.DeclStmt: 135 | return 1 << nDeclStmt 136 | case *ast.DeferStmt: 137 | return 1 << nDeferStmt 138 | case *ast.Ellipsis: 139 | return 1 << nEllipsis 140 | case *ast.EmptyStmt: 141 | return 1 << nEmptyStmt 142 | case *ast.ExprStmt: 143 | return 1 << nExprStmt 144 | case *ast.Field: 145 | return 1 << nField 146 | case *ast.FieldList: 147 | return 1 << nFieldList 148 | case *ast.File: 149 | return 1 << nFile 150 | case *ast.ForStmt: 151 | return 1 << nForStmt 152 | case *ast.FuncDecl: 153 | return 1 << nFuncDecl 154 | case *ast.FuncLit: 155 | return 1 << nFuncLit 156 | case *ast.FuncType: 157 | return 1 << nFuncType 158 | case *ast.GenDecl: 159 | return 1 << nGenDecl 160 | case *ast.GoStmt: 161 | return 1 << nGoStmt 162 | case *ast.Ident: 163 | return 1 << nIdent 164 | case *ast.IfStmt: 165 | return 1 << nIfStmt 166 | case *ast.ImportSpec: 167 | return 1 << nImportSpec 168 | case *ast.IncDecStmt: 169 | return 1 << nIncDecStmt 170 | case *ast.IndexExpr: 171 | return 1 << nIndexExpr 172 | case *ast.IndexListExpr: 173 | return 1 << nIndexListExpr 174 | case *ast.InterfaceType: 175 | return 1 << nInterfaceType 176 | case *ast.KeyValueExpr: 177 | return 1 << nKeyValueExpr 178 | case *ast.LabeledStmt: 179 | return 1 << nLabeledStmt 180 | case *ast.MapType: 181 | return 1 << nMapType 182 | case *ast.Package: 183 | return 1 << nPackage 184 | case *ast.ParenExpr: 185 | return 1 << nParenExpr 186 | case *ast.RangeStmt: 187 | return 1 << nRangeStmt 188 | case *ast.ReturnStmt: 189 | return 1 << nReturnStmt 190 | case *ast.SelectStmt: 191 | return 1 << nSelectStmt 192 | case *ast.SelectorExpr: 193 | return 1 << nSelectorExpr 194 | case *ast.SendStmt: 195 | return 1 << nSendStmt 196 | case *ast.SliceExpr: 197 | return 1 << nSliceExpr 198 | case *ast.StarExpr: 199 | return 1 << nStarExpr 200 | case *ast.StructType: 201 | return 1 << nStructType 202 | case *ast.SwitchStmt: 203 | return 1 << nSwitchStmt 204 | case *ast.TypeAssertExpr: 205 | return 1 << nTypeAssertExpr 206 | case *ast.TypeSpec: 207 | return 1 << nTypeSpec 208 | case *ast.TypeSwitchStmt: 209 | return 1 << nTypeSwitchStmt 210 | case *ast.UnaryExpr: 211 | return 1 << nUnaryExpr 212 | case *ast.ValueSpec: 213 | return 1 << nValueSpec 214 | } 215 | return 0 216 | } 217 | 218 | func maskOf(nodes []ast.Node) uint64 { 219 | if nodes == nil { 220 | return math.MaxUint64 // match all node types 221 | } 222 | var mask uint64 223 | for _, n := range nodes { 224 | mask |= typeOf(n) 225 | } 226 | return mask 227 | } 228 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/gcexportdata/importer.go: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package gcexportdata 6 | 7 | import ( 8 | "fmt" 9 | "go/token" 10 | "go/types" 11 | "os" 12 | ) 13 | 14 | // NewImporter returns a new instance of the types.Importer interface 15 | // that reads type information from export data files written by gc. 16 | // The Importer also satisfies types.ImporterFrom. 17 | // 18 | // Export data files are located using "go build" workspace conventions 19 | // and the build.Default context. 20 | // 21 | // Use this importer instead of go/importer.For("gc", ...) to avoid the 22 | // version-skew problems described in the documentation of this package, 23 | // or to control the FileSet or access the imports map populated during 24 | // package loading. 25 | // 26 | // Deprecated: Use the higher-level API in golang.org/x/tools/go/packages, 27 | // which is more efficient. 28 | func NewImporter(fset *token.FileSet, imports map[string]*types.Package) types.ImporterFrom { 29 | return importer{fset, imports} 30 | } 31 | 32 | type importer struct { 33 | fset *token.FileSet 34 | imports map[string]*types.Package 35 | } 36 | 37 | func (imp importer) Import(importPath string) (*types.Package, error) { 38 | return imp.ImportFrom(importPath, "", 0) 39 | } 40 | 41 | func (imp importer) ImportFrom(importPath, srcDir string, mode types.ImportMode) (_ *types.Package, err error) { 42 | filename, path := Find(importPath, srcDir) 43 | if filename == "" { 44 | if importPath == "unsafe" { 45 | // Even for unsafe, call Find first in case 46 | // the package was vendored. 47 | return types.Unsafe, nil 48 | } 49 | return nil, fmt.Errorf("can't find import: %s", importPath) 50 | } 51 | 52 | if pkg, ok := imp.imports[path]; ok && pkg.Complete() { 53 | return pkg, nil // cache hit 54 | } 55 | 56 | // open file 57 | f, err := os.Open(filename) 58 | if err != nil { 59 | return nil, err 60 | } 61 | defer func() { 62 | f.Close() 63 | if err != nil { 64 | // add file name to error 65 | err = fmt.Errorf("reading export data: %s: %v", filename, err) 66 | } 67 | }() 68 | 69 | r, err := NewReader(f) 70 | if err != nil { 71 | return nil, err 72 | } 73 | 74 | return Read(r, imp.fset, imp.imports, path) 75 | } 76 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/packages/golist_overlay.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packages 6 | 7 | import ( 8 | "encoding/json" 9 | "path/filepath" 10 | 11 | "golang.org/x/tools/internal/gocommand" 12 | ) 13 | 14 | // determineRootDirs returns a mapping from absolute directories that could 15 | // contain code to their corresponding import path prefixes. 16 | func (state *golistState) determineRootDirs() (map[string]string, error) { 17 | env, err := state.getEnv() 18 | if err != nil { 19 | return nil, err 20 | } 21 | if env["GOMOD"] != "" { 22 | state.rootsOnce.Do(func() { 23 | state.rootDirs, state.rootDirsError = state.determineRootDirsModules() 24 | }) 25 | } else { 26 | state.rootsOnce.Do(func() { 27 | state.rootDirs, state.rootDirsError = state.determineRootDirsGOPATH() 28 | }) 29 | } 30 | return state.rootDirs, state.rootDirsError 31 | } 32 | 33 | func (state *golistState) determineRootDirsModules() (map[string]string, error) { 34 | // List all of the modules--the first will be the directory for the main 35 | // module. Any replaced modules will also need to be treated as roots. 36 | // Editing files in the module cache isn't a great idea, so we don't 37 | // plan to ever support that. 38 | out, err := state.invokeGo("list", "-m", "-json", "all") 39 | if err != nil { 40 | // 'go list all' will fail if we're outside of a module and 41 | // GO111MODULE=on. Try falling back without 'all'. 42 | var innerErr error 43 | out, innerErr = state.invokeGo("list", "-m", "-json") 44 | if innerErr != nil { 45 | return nil, err 46 | } 47 | } 48 | roots := map[string]string{} 49 | modules := map[string]string{} 50 | var i int 51 | for dec := json.NewDecoder(out); dec.More(); { 52 | mod := new(gocommand.ModuleJSON) 53 | if err := dec.Decode(mod); err != nil { 54 | return nil, err 55 | } 56 | if mod.Dir != "" && mod.Path != "" { 57 | // This is a valid module; add it to the map. 58 | absDir, err := filepath.Abs(mod.Dir) 59 | if err != nil { 60 | return nil, err 61 | } 62 | modules[absDir] = mod.Path 63 | // The first result is the main module. 64 | if i == 0 || mod.Replace != nil && mod.Replace.Path != "" { 65 | roots[absDir] = mod.Path 66 | } 67 | } 68 | i++ 69 | } 70 | return roots, nil 71 | } 72 | 73 | func (state *golistState) determineRootDirsGOPATH() (map[string]string, error) { 74 | m := map[string]string{} 75 | for _, dir := range filepath.SplitList(state.mustGetEnv()["GOPATH"]) { 76 | absDir, err := filepath.Abs(dir) 77 | if err != nil { 78 | return nil, err 79 | } 80 | m[filepath.Join(absDir, "src")] = "" 81 | } 82 | return m, nil 83 | } 84 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/packages/loadmode_string.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packages 6 | 7 | import ( 8 | "fmt" 9 | "strings" 10 | ) 11 | 12 | var modes = [...]struct { 13 | mode LoadMode 14 | name string 15 | }{ 16 | {NeedName, "NeedName"}, 17 | {NeedFiles, "NeedFiles"}, 18 | {NeedCompiledGoFiles, "NeedCompiledGoFiles"}, 19 | {NeedImports, "NeedImports"}, 20 | {NeedDeps, "NeedDeps"}, 21 | {NeedExportFile, "NeedExportFile"}, 22 | {NeedTypes, "NeedTypes"}, 23 | {NeedSyntax, "NeedSyntax"}, 24 | {NeedTypesInfo, "NeedTypesInfo"}, 25 | {NeedTypesSizes, "NeedTypesSizes"}, 26 | {NeedModule, "NeedModule"}, 27 | {NeedEmbedFiles, "NeedEmbedFiles"}, 28 | {NeedEmbedPatterns, "NeedEmbedPatterns"}, 29 | } 30 | 31 | func (mode LoadMode) String() string { 32 | if mode == 0 { 33 | return "LoadMode(0)" 34 | } 35 | var out []string 36 | // named bits 37 | for _, item := range modes { 38 | if (mode & item.mode) != 0 { 39 | mode ^= item.mode 40 | out = append(out, item.name) 41 | } 42 | } 43 | // unnamed residue 44 | if mode != 0 { 45 | if out == nil { 46 | return fmt.Sprintf("LoadMode(%#x)", int(mode)) 47 | } 48 | out = append(out, fmt.Sprintf("%#x", int(mode))) 49 | } 50 | if len(out) == 1 { 51 | return out[0] 52 | } 53 | return "(" + strings.Join(out, "|") + ")" 54 | } 55 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/packages/visit.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package packages 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | "sort" 11 | ) 12 | 13 | // Visit visits all the packages in the import graph whose roots are 14 | // pkgs, calling the optional pre function the first time each package 15 | // is encountered (preorder), and the optional post function after a 16 | // package's dependencies have been visited (postorder). 17 | // The boolean result of pre(pkg) determines whether 18 | // the imports of package pkg are visited. 19 | func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) { 20 | seen := make(map[*Package]bool) 21 | var visit func(*Package) 22 | visit = func(pkg *Package) { 23 | if !seen[pkg] { 24 | seen[pkg] = true 25 | 26 | if pre == nil || pre(pkg) { 27 | paths := make([]string, 0, len(pkg.Imports)) 28 | for path := range pkg.Imports { 29 | paths = append(paths, path) 30 | } 31 | sort.Strings(paths) // Imports is a map, this makes visit stable 32 | for _, path := range paths { 33 | visit(pkg.Imports[path]) 34 | } 35 | } 36 | 37 | if post != nil { 38 | post(pkg) 39 | } 40 | } 41 | } 42 | for _, pkg := range pkgs { 43 | visit(pkg) 44 | } 45 | } 46 | 47 | // PrintErrors prints to os.Stderr the accumulated errors of all 48 | // packages in the import graph rooted at pkgs, dependencies first. 49 | // PrintErrors returns the number of errors printed. 50 | func PrintErrors(pkgs []*Package) int { 51 | var n int 52 | errModules := make(map[*Module]bool) 53 | Visit(pkgs, nil, func(pkg *Package) { 54 | for _, err := range pkg.Errors { 55 | fmt.Fprintln(os.Stderr, err) 56 | n++ 57 | } 58 | 59 | // Print pkg.Module.Error once if present. 60 | mod := pkg.Module 61 | if mod != nil && mod.Error != nil && !errModules[mod] { 62 | errModules[mod] = true 63 | fmt.Fprintln(os.Stderr, mod.Error.Err) 64 | n++ 65 | } 66 | }) 67 | return n 68 | } 69 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/types/typeutil/callee.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typeutil 6 | 7 | import ( 8 | "go/ast" 9 | "go/types" 10 | 11 | "golang.org/x/tools/internal/typeparams" 12 | ) 13 | 14 | // Callee returns the named target of a function call, if any: 15 | // a function, method, builtin, or variable. 16 | // 17 | // Functions and methods may potentially have type parameters. 18 | func Callee(info *types.Info, call *ast.CallExpr) types.Object { 19 | fun := ast.Unparen(call.Fun) 20 | 21 | // Look through type instantiation if necessary. 22 | isInstance := false 23 | switch fun.(type) { 24 | case *ast.IndexExpr, *ast.IndexListExpr: 25 | // When extracting the callee from an *IndexExpr, we need to check that 26 | // it is a *types.Func and not a *types.Var. 27 | // Example: Don't match a slice m within the expression `m[0]()`. 28 | isInstance = true 29 | fun, _, _, _ = typeparams.UnpackIndexExpr(fun) 30 | } 31 | 32 | var obj types.Object 33 | switch fun := fun.(type) { 34 | case *ast.Ident: 35 | obj = info.Uses[fun] // type, var, builtin, or declared func 36 | case *ast.SelectorExpr: 37 | if sel, ok := info.Selections[fun]; ok { 38 | obj = sel.Obj() // method or field 39 | } else { 40 | obj = info.Uses[fun.Sel] // qualified identifier? 41 | } 42 | } 43 | if _, ok := obj.(*types.TypeName); ok { 44 | return nil // T(x) is a conversion, not a call 45 | } 46 | // A Func is required to match instantiations. 47 | if _, ok := obj.(*types.Func); isInstance && !ok { 48 | return nil // Was not a Func. 49 | } 50 | return obj 51 | } 52 | 53 | // StaticCallee returns the target (function or method) of a static function 54 | // call, if any. It returns nil for calls to builtins. 55 | // 56 | // Note: for calls of instantiated functions and methods, StaticCallee returns 57 | // the corresponding generic function or method on the generic type. 58 | func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func { 59 | if f, ok := Callee(info, call).(*types.Func); ok && !interfaceMethod(f) { 60 | return f 61 | } 62 | return nil 63 | } 64 | 65 | func interfaceMethod(f *types.Func) bool { 66 | recv := f.Type().(*types.Signature).Recv() 67 | return recv != nil && types.IsInterface(recv.Type()) 68 | } 69 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/types/typeutil/imports.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typeutil 6 | 7 | import "go/types" 8 | 9 | // Dependencies returns all dependencies of the specified packages. 10 | // 11 | // Dependent packages appear in topological order: if package P imports 12 | // package Q, Q appears earlier than P in the result. 13 | // The algorithm follows import statements in the order they 14 | // appear in the source code, so the result is a total order. 15 | func Dependencies(pkgs ...*types.Package) []*types.Package { 16 | var result []*types.Package 17 | seen := make(map[*types.Package]bool) 18 | var visit func(pkgs []*types.Package) 19 | visit = func(pkgs []*types.Package) { 20 | for _, p := range pkgs { 21 | if !seen[p] { 22 | seen[p] = true 23 | visit(p.Imports()) 24 | result = append(result, p) 25 | } 26 | } 27 | } 28 | visit(pkgs) 29 | return result 30 | } 31 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/types/typeutil/methodsetcache.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This file implements a cache of method sets. 6 | 7 | package typeutil 8 | 9 | import ( 10 | "go/types" 11 | "sync" 12 | ) 13 | 14 | // A MethodSetCache records the method set of each type T for which 15 | // MethodSet(T) is called so that repeat queries are fast. 16 | // The zero value is a ready-to-use cache instance. 17 | type MethodSetCache struct { 18 | mu sync.Mutex 19 | named map[*types.Named]struct{ value, pointer *types.MethodSet } // method sets for named N and *N 20 | others map[types.Type]*types.MethodSet // all other types 21 | } 22 | 23 | // MethodSet returns the method set of type T. It is thread-safe. 24 | // 25 | // If cache is nil, this function is equivalent to types.NewMethodSet(T). 26 | // Utility functions can thus expose an optional *MethodSetCache 27 | // parameter to clients that care about performance. 28 | func (cache *MethodSetCache) MethodSet(T types.Type) *types.MethodSet { 29 | if cache == nil { 30 | return types.NewMethodSet(T) 31 | } 32 | cache.mu.Lock() 33 | defer cache.mu.Unlock() 34 | 35 | switch T := types.Unalias(T).(type) { 36 | case *types.Named: 37 | return cache.lookupNamed(T).value 38 | 39 | case *types.Pointer: 40 | if N, ok := types.Unalias(T.Elem()).(*types.Named); ok { 41 | return cache.lookupNamed(N).pointer 42 | } 43 | } 44 | 45 | // all other types 46 | // (The map uses pointer equivalence, not type identity.) 47 | mset := cache.others[T] 48 | if mset == nil { 49 | mset = types.NewMethodSet(T) 50 | if cache.others == nil { 51 | cache.others = make(map[types.Type]*types.MethodSet) 52 | } 53 | cache.others[T] = mset 54 | } 55 | return mset 56 | } 57 | 58 | func (cache *MethodSetCache) lookupNamed(named *types.Named) struct{ value, pointer *types.MethodSet } { 59 | if cache.named == nil { 60 | cache.named = make(map[*types.Named]struct{ value, pointer *types.MethodSet }) 61 | } 62 | // Avoid recomputing mset(*T) for each distinct Pointer 63 | // instance whose underlying type is a named type. 64 | msets, ok := cache.named[named] 65 | if !ok { 66 | msets.value = types.NewMethodSet(named) 67 | msets.pointer = types.NewMethodSet(types.NewPointer(named)) 68 | cache.named[named] = msets 69 | } 70 | return msets 71 | } 72 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/go/types/typeutil/ui.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typeutil 6 | 7 | // This file defines utilities for user interfaces that display types. 8 | 9 | import ( 10 | "go/types" 11 | ) 12 | 13 | // IntuitiveMethodSet returns the intuitive method set of a type T, 14 | // which is the set of methods you can call on an addressable value of 15 | // that type. 16 | // 17 | // The result always contains MethodSet(T), and is exactly MethodSet(T) 18 | // for interface types and for pointer-to-concrete types. 19 | // For all other concrete types T, the result additionally 20 | // contains each method belonging to *T if there is no identically 21 | // named method on T itself. 22 | // 23 | // This corresponds to user intuition about method sets; 24 | // this function is intended only for user interfaces. 25 | // 26 | // The order of the result is as for types.MethodSet(T). 27 | func IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection { 28 | isPointerToConcrete := func(T types.Type) bool { 29 | ptr, ok := types.Unalias(T).(*types.Pointer) 30 | return ok && !types.IsInterface(ptr.Elem()) 31 | } 32 | 33 | var result []*types.Selection 34 | mset := msets.MethodSet(T) 35 | if types.IsInterface(T) || isPointerToConcrete(T) { 36 | for i, n := 0, mset.Len(); i < n; i++ { 37 | result = append(result, mset.At(i)) 38 | } 39 | } else { 40 | // T is some other concrete type. 41 | // Report methods of T and *T, preferring those of T. 42 | pmset := msets.MethodSet(types.NewPointer(T)) 43 | for i, n := 0, pmset.Len(); i < n; i++ { 44 | meth := pmset.At(i) 45 | if m := mset.Lookup(meth.Obj().Pkg(), meth.Obj().Name()); m != nil { 46 | meth = m 47 | } 48 | result = append(result, meth) 49 | } 50 | 51 | } 52 | return result 53 | } 54 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/aliases/aliases.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package aliases 6 | 7 | import ( 8 | "go/token" 9 | "go/types" 10 | ) 11 | 12 | // Package aliases defines backward compatible shims 13 | // for the types.Alias type representation added in 1.22. 14 | // This defines placeholders for x/tools until 1.26. 15 | 16 | // NewAlias creates a new TypeName in Package pkg that 17 | // is an alias for the type rhs. 18 | // 19 | // The enabled parameter determines whether the resulting [TypeName]'s 20 | // type is an [types.Alias]. Its value must be the result of a call to 21 | // [Enabled], which computes the effective value of 22 | // GODEBUG=gotypesalias=... by invoking the type checker. The Enabled 23 | // function is expensive and should be called once per task (e.g. 24 | // package import), not once per call to NewAlias. 25 | // 26 | // Precondition: enabled || len(tparams)==0. 27 | // If materialized aliases are disabled, there must not be any type parameters. 28 | func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type, tparams []*types.TypeParam) *types.TypeName { 29 | if enabled { 30 | tname := types.NewTypeName(pos, pkg, name, nil) 31 | SetTypeParams(types.NewAlias(tname, rhs), tparams) 32 | return tname 33 | } 34 | if len(tparams) > 0 { 35 | panic("cannot create an alias with type parameters when gotypesalias is not enabled") 36 | } 37 | return types.NewTypeName(pos, pkg, name, rhs) 38 | } 39 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/aliases/aliases_go122.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package aliases 6 | 7 | import ( 8 | "go/ast" 9 | "go/parser" 10 | "go/token" 11 | "go/types" 12 | ) 13 | 14 | // Rhs returns the type on the right-hand side of the alias declaration. 15 | func Rhs(alias *types.Alias) types.Type { 16 | if alias, ok := any(alias).(interface{ Rhs() types.Type }); ok { 17 | return alias.Rhs() // go1.23+ 18 | } 19 | 20 | // go1.22's Alias didn't have the Rhs method, 21 | // so Unalias is the best we can do. 22 | return types.Unalias(alias) 23 | } 24 | 25 | // TypeParams returns the type parameter list of the alias. 26 | func TypeParams(alias *types.Alias) *types.TypeParamList { 27 | if alias, ok := any(alias).(interface{ TypeParams() *types.TypeParamList }); ok { 28 | return alias.TypeParams() // go1.23+ 29 | } 30 | return nil 31 | } 32 | 33 | // SetTypeParams sets the type parameters of the alias type. 34 | func SetTypeParams(alias *types.Alias, tparams []*types.TypeParam) { 35 | if alias, ok := any(alias).(interface { 36 | SetTypeParams(tparams []*types.TypeParam) 37 | }); ok { 38 | alias.SetTypeParams(tparams) // go1.23+ 39 | } else if len(tparams) > 0 { 40 | panic("cannot set type parameters of an Alias type in go1.22") 41 | } 42 | } 43 | 44 | // TypeArgs returns the type arguments used to instantiate the Alias type. 45 | func TypeArgs(alias *types.Alias) *types.TypeList { 46 | if alias, ok := any(alias).(interface{ TypeArgs() *types.TypeList }); ok { 47 | return alias.TypeArgs() // go1.23+ 48 | } 49 | return nil // empty (go1.22) 50 | } 51 | 52 | // Origin returns the generic Alias type of which alias is an instance. 53 | // If alias is not an instance of a generic alias, Origin returns alias. 54 | func Origin(alias *types.Alias) *types.Alias { 55 | if alias, ok := any(alias).(interface{ Origin() *types.Alias }); ok { 56 | return alias.Origin() // go1.23+ 57 | } 58 | return alias // not an instance of a generic alias (go1.22) 59 | } 60 | 61 | // Enabled reports whether [NewAlias] should create [types.Alias] types. 62 | // 63 | // This function is expensive! Call it sparingly. 64 | func Enabled() bool { 65 | // The only reliable way to compute the answer is to invoke go/types. 66 | // We don't parse the GODEBUG environment variable, because 67 | // (a) it's tricky to do so in a manner that is consistent 68 | // with the godebug package; in particular, a simple 69 | // substring check is not good enough. The value is a 70 | // rightmost-wins list of options. But more importantly: 71 | // (b) it is impossible to detect changes to the effective 72 | // setting caused by os.Setenv("GODEBUG"), as happens in 73 | // many tests. Therefore any attempt to cache the result 74 | // is just incorrect. 75 | fset := token.NewFileSet() 76 | f, _ := parser.ParseFile(fset, "a.go", "package p; type A = int", parser.SkipObjectResolution) 77 | pkg, _ := new(types.Config).Check("p", fset, []*ast.File{f}, nil) 78 | _, enabled := pkg.Scope().Lookup("A").Type().(*types.Alias) 79 | return enabled 80 | } 81 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/analysisinternal/extractdoc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package analysisinternal 6 | 7 | import ( 8 | "fmt" 9 | "go/parser" 10 | "go/token" 11 | "strings" 12 | ) 13 | 14 | // MustExtractDoc is like [ExtractDoc] but it panics on error. 15 | // 16 | // To use, define a doc.go file such as: 17 | // 18 | // // Package halting defines an analyzer of program termination. 19 | // // 20 | // // # Analyzer halting 21 | // // 22 | // // halting: reports whether execution will halt. 23 | // // 24 | // // The halting analyzer reports a diagnostic for functions 25 | // // that run forever. To suppress the diagnostics, try inserting 26 | // // a 'break' statement into each loop. 27 | // package halting 28 | // 29 | // import _ "embed" 30 | // 31 | // //go:embed doc.go 32 | // var doc string 33 | // 34 | // And declare your analyzer as: 35 | // 36 | // var Analyzer = &analysis.Analyzer{ 37 | // Name: "halting", 38 | // Doc: analysisutil.MustExtractDoc(doc, "halting"), 39 | // ... 40 | // } 41 | func MustExtractDoc(content, name string) string { 42 | doc, err := ExtractDoc(content, name) 43 | if err != nil { 44 | panic(err) 45 | } 46 | return doc 47 | } 48 | 49 | // ExtractDoc extracts a section of a package doc comment from the 50 | // provided contents of an analyzer package's doc.go file. 51 | // 52 | // A section is a portion of the comment between one heading and 53 | // the next, using this form: 54 | // 55 | // # Analyzer NAME 56 | // 57 | // NAME: SUMMARY 58 | // 59 | // Full description... 60 | // 61 | // where NAME matches the name argument, and SUMMARY is a brief 62 | // verb-phrase that describes the analyzer. The following lines, up 63 | // until the next heading or the end of the comment, contain the full 64 | // description. ExtractDoc returns the portion following the colon, 65 | // which is the form expected by Analyzer.Doc. 66 | // 67 | // Example: 68 | // 69 | // # Analyzer printf 70 | // 71 | // printf: checks consistency of calls to printf 72 | // 73 | // The printf analyzer checks consistency of calls to printf. 74 | // Here is the complete description... 75 | // 76 | // This notation allows a single doc comment to provide documentation 77 | // for multiple analyzers, each in its own section. 78 | // The HTML anchors generated for each heading are predictable. 79 | // 80 | // It returns an error if the content was not a valid Go source file 81 | // containing a package doc comment with a heading of the required 82 | // form. 83 | // 84 | // This machinery enables the package documentation (typically 85 | // accessible via the web at https://pkg.go.dev/) and the command 86 | // documentation (typically printed to a terminal) to be derived from 87 | // the same source and formatted appropriately. 88 | func ExtractDoc(content, name string) (string, error) { 89 | if content == "" { 90 | return "", fmt.Errorf("empty Go source file") 91 | } 92 | fset := token.NewFileSet() 93 | f, err := parser.ParseFile(fset, "", content, parser.ParseComments|parser.PackageClauseOnly) 94 | if err != nil { 95 | return "", fmt.Errorf("not a Go source file") 96 | } 97 | if f.Doc == nil { 98 | return "", fmt.Errorf("Go source file has no package doc comment") 99 | } 100 | for _, section := range strings.Split(f.Doc.Text(), "\n# ") { 101 | if body := strings.TrimPrefix(section, "Analyzer "+name); body != section && 102 | body != "" && 103 | body[0] == '\r' || body[0] == '\n' { 104 | body = strings.TrimSpace(body) 105 | rest := strings.TrimPrefix(body, name+":") 106 | if rest == body { 107 | return "", fmt.Errorf("'Analyzer %s' heading not followed by '%s: summary...' line", name, name) 108 | } 109 | return strings.TrimSpace(rest), nil 110 | } 111 | } 112 | return "", fmt.Errorf("package doc comment contains no 'Analyzer %s' heading", name) 113 | } 114 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/diff/diff.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package diff computes differences between text files or strings. 6 | package diff 7 | 8 | import ( 9 | "fmt" 10 | "sort" 11 | "strings" 12 | ) 13 | 14 | // An Edit describes the replacement of a portion of a text file. 15 | type Edit struct { 16 | Start, End int // byte offsets of the region to replace 17 | New string // the replacement 18 | } 19 | 20 | func (e Edit) String() string { 21 | return fmt.Sprintf("{Start:%d,End:%d,New:%q}", e.Start, e.End, e.New) 22 | } 23 | 24 | // Apply applies a sequence of edits to the src buffer and returns the 25 | // result. Edits are applied in order of start offset; edits with the 26 | // same start offset are applied in they order they were provided. 27 | // 28 | // Apply returns an error if any edit is out of bounds, 29 | // or if any pair of edits is overlapping. 30 | func Apply(src string, edits []Edit) (string, error) { 31 | edits, size, err := validate(src, edits) 32 | if err != nil { 33 | return "", err 34 | } 35 | 36 | // Apply edits. 37 | out := make([]byte, 0, size) 38 | lastEnd := 0 39 | for _, edit := range edits { 40 | if lastEnd < edit.Start { 41 | out = append(out, src[lastEnd:edit.Start]...) 42 | } 43 | out = append(out, edit.New...) 44 | lastEnd = edit.End 45 | } 46 | out = append(out, src[lastEnd:]...) 47 | 48 | if len(out) != size { 49 | panic("wrong size") 50 | } 51 | 52 | return string(out), nil 53 | } 54 | 55 | // ApplyBytes is like Apply, but it accepts a byte slice. 56 | // The result is always a new array. 57 | func ApplyBytes(src []byte, edits []Edit) ([]byte, error) { 58 | res, err := Apply(string(src), edits) 59 | return []byte(res), err 60 | } 61 | 62 | // validate checks that edits are consistent with src, 63 | // and returns the size of the patched output. 64 | // It may return a different slice. 65 | func validate(src string, edits []Edit) ([]Edit, int, error) { 66 | if !sort.IsSorted(editsSort(edits)) { 67 | edits = append([]Edit(nil), edits...) 68 | SortEdits(edits) 69 | } 70 | 71 | // Check validity of edits and compute final size. 72 | size := len(src) 73 | lastEnd := 0 74 | for _, edit := range edits { 75 | if !(0 <= edit.Start && edit.Start <= edit.End && edit.End <= len(src)) { 76 | return nil, 0, fmt.Errorf("diff has out-of-bounds edits") 77 | } 78 | if edit.Start < lastEnd { 79 | return nil, 0, fmt.Errorf("diff has overlapping edits") 80 | } 81 | size += len(edit.New) + edit.Start - edit.End 82 | lastEnd = edit.End 83 | } 84 | 85 | return edits, size, nil 86 | } 87 | 88 | // SortEdits orders a slice of Edits by (start, end) offset. 89 | // This ordering puts insertions (end = start) before deletions 90 | // (end > start) at the same point, but uses a stable sort to preserve 91 | // the order of multiple insertions at the same point. 92 | // (Apply detects multiple deletions at the same point as an error.) 93 | func SortEdits(edits []Edit) { 94 | sort.Stable(editsSort(edits)) 95 | } 96 | 97 | type editsSort []Edit 98 | 99 | func (a editsSort) Len() int { return len(a) } 100 | func (a editsSort) Less(i, j int) bool { 101 | if cmp := a[i].Start - a[j].Start; cmp != 0 { 102 | return cmp < 0 103 | } 104 | return a[i].End < a[j].End 105 | } 106 | func (a editsSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] } 107 | 108 | // lineEdits expands and merges a sequence of edits so that each 109 | // resulting edit replaces one or more complete lines. 110 | // See ApplyEdits for preconditions. 111 | func lineEdits(src string, edits []Edit) ([]Edit, error) { 112 | edits, _, err := validate(src, edits) 113 | if err != nil { 114 | return nil, err 115 | } 116 | 117 | // Do all deletions begin and end at the start of a line, 118 | // and all insertions end with a newline? 119 | // (This is merely a fast path.) 120 | for _, edit := range edits { 121 | if edit.Start >= len(src) || // insertion at EOF 122 | edit.Start > 0 && src[edit.Start-1] != '\n' || // not at line start 123 | edit.End > 0 && src[edit.End-1] != '\n' || // not at line start 124 | edit.New != "" && edit.New[len(edit.New)-1] != '\n' { // partial insert 125 | goto expand // slow path 126 | } 127 | } 128 | return edits, nil // aligned 129 | 130 | expand: 131 | if len(edits) == 0 { 132 | return edits, nil // no edits (unreachable due to fast path) 133 | } 134 | expanded := make([]Edit, 0, len(edits)) // a guess 135 | prev := edits[0] 136 | // TODO(adonovan): opt: start from the first misaligned edit. 137 | // TODO(adonovan): opt: avoid quadratic cost of string += string. 138 | for _, edit := range edits[1:] { 139 | between := src[prev.End:edit.Start] 140 | if !strings.Contains(between, "\n") { 141 | // overlapping lines: combine with previous edit. 142 | prev.New += between + edit.New 143 | prev.End = edit.End 144 | } else { 145 | // non-overlapping lines: flush previous edit. 146 | expanded = append(expanded, expandEdit(prev, src)) 147 | prev = edit 148 | } 149 | } 150 | return append(expanded, expandEdit(prev, src)), nil // flush final edit 151 | } 152 | 153 | // expandEdit returns edit expanded to complete whole lines. 154 | func expandEdit(edit Edit, src string) Edit { 155 | // Expand start left to start of line. 156 | // (delta is the zero-based column number of start.) 157 | start := edit.Start 158 | if delta := start - 1 - strings.LastIndex(src[:start], "\n"); delta > 0 { 159 | edit.Start -= delta 160 | edit.New = src[start-delta:start] + edit.New 161 | } 162 | 163 | // Expand end right to end of line. 164 | end := edit.End 165 | if end > 0 && src[end-1] != '\n' || 166 | edit.New != "" && edit.New[len(edit.New)-1] != '\n' { 167 | if nl := strings.IndexByte(src[end:], '\n'); nl < 0 { 168 | edit.End = len(src) // extend to EOF 169 | } else { 170 | edit.End = end + nl + 1 // extend beyond \n 171 | } 172 | } 173 | edit.New += src[end:edit.End] 174 | 175 | return edit 176 | } 177 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/diff/lcs/common.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package lcs 6 | 7 | import ( 8 | "log" 9 | "sort" 10 | ) 11 | 12 | // lcs is a longest common sequence 13 | type lcs []diag 14 | 15 | // A diag is a piece of the edit graph where A[X+i] == B[Y+i], for 0<=i l[j].Len 29 | }) 30 | return l 31 | } 32 | 33 | // validate that the elements of the lcs do not overlap 34 | // (can only happen when the two-sided algorithm ends early) 35 | // expects the lcs to be sorted 36 | func (l lcs) valid() bool { 37 | for i := 1; i < len(l); i++ { 38 | if l[i-1].X+l[i-1].Len > l[i].X { 39 | return false 40 | } 41 | if l[i-1].Y+l[i-1].Len > l[i].Y { 42 | return false 43 | } 44 | } 45 | return true 46 | } 47 | 48 | // repair overlapping lcs 49 | // only called if two-sided stops early 50 | func (l lcs) fix() lcs { 51 | // from the set of diagonals in l, find a maximal non-conflicting set 52 | // this problem may be NP-complete, but we use a greedy heuristic, 53 | // which is quadratic, but with a better data structure, could be D log D. 54 | // indepedent is not enough: {0,3,1} and {3,0,2} can't both occur in an lcs 55 | // which has to have monotone x and y 56 | if len(l) == 0 { 57 | return nil 58 | } 59 | sort.Slice(l, func(i, j int) bool { return l[i].Len > l[j].Len }) 60 | tmp := make(lcs, 0, len(l)) 61 | tmp = append(tmp, l[0]) 62 | for i := 1; i < len(l); i++ { 63 | var dir direction 64 | nxt := l[i] 65 | for _, in := range tmp { 66 | if dir, nxt = overlap(in, nxt); dir == empty || dir == bad { 67 | break 68 | } 69 | } 70 | if nxt.Len > 0 && dir != bad { 71 | tmp = append(tmp, nxt) 72 | } 73 | } 74 | tmp.sort() 75 | if false && !tmp.valid() { // debug checking 76 | log.Fatalf("here %d", len(tmp)) 77 | } 78 | return tmp 79 | } 80 | 81 | type direction int 82 | 83 | const ( 84 | empty direction = iota // diag is empty (so not in lcs) 85 | leftdown // proposed acceptably to the left and below 86 | rightup // proposed diag is acceptably to the right and above 87 | bad // proposed diag is inconsistent with the lcs so far 88 | ) 89 | 90 | // overlap trims the proposed diag prop so it doesn't overlap with 91 | // the existing diag that has already been added to the lcs. 92 | func overlap(exist, prop diag) (direction, diag) { 93 | if prop.X <= exist.X && exist.X < prop.X+prop.Len { 94 | // remove the end of prop where it overlaps with the X end of exist 95 | delta := prop.X + prop.Len - exist.X 96 | prop.Len -= delta 97 | if prop.Len <= 0 { 98 | return empty, prop 99 | } 100 | } 101 | if exist.X <= prop.X && prop.X < exist.X+exist.Len { 102 | // remove the beginning of prop where overlaps with exist 103 | delta := exist.X + exist.Len - prop.X 104 | prop.Len -= delta 105 | if prop.Len <= 0 { 106 | return empty, prop 107 | } 108 | prop.X += delta 109 | prop.Y += delta 110 | } 111 | if prop.Y <= exist.Y && exist.Y < prop.Y+prop.Len { 112 | // remove the end of prop that overlaps (in Y) with exist 113 | delta := prop.Y + prop.Len - exist.Y 114 | prop.Len -= delta 115 | if prop.Len <= 0 { 116 | return empty, prop 117 | } 118 | } 119 | if exist.Y <= prop.Y && prop.Y < exist.Y+exist.Len { 120 | // remove the beginning of peop that overlaps with exist 121 | delta := exist.Y + exist.Len - prop.Y 122 | prop.Len -= delta 123 | if prop.Len <= 0 { 124 | return empty, prop 125 | } 126 | prop.X += delta // no test reaches this code 127 | prop.Y += delta 128 | } 129 | if prop.X+prop.Len <= exist.X && prop.Y+prop.Len <= exist.Y { 130 | return leftdown, prop 131 | } 132 | if exist.X+exist.Len <= prop.X && exist.Y+exist.Len <= prop.Y { 133 | return rightup, prop 134 | } 135 | // prop can't be in an lcs that contains exist 136 | return bad, prop 137 | } 138 | 139 | // manipulating Diag and lcs 140 | 141 | // prepend a diagonal (x,y)-(x+1,y+1) segment either to an empty lcs 142 | // or to its first Diag. prepend is only called to extend diagonals 143 | // the backward direction. 144 | func (lcs lcs) prepend(x, y int) lcs { 145 | if len(lcs) > 0 { 146 | d := &lcs[0] 147 | if int(d.X) == x+1 && int(d.Y) == y+1 { 148 | // extend the diagonal down and to the left 149 | d.X, d.Y = int(x), int(y) 150 | d.Len++ 151 | return lcs 152 | } 153 | } 154 | 155 | r := diag{X: int(x), Y: int(y), Len: 1} 156 | lcs = append([]diag{r}, lcs...) 157 | return lcs 158 | } 159 | 160 | // append appends a diagonal, or extends the existing one. 161 | // by adding the edge (x,y)-(x+1.y+1). append is only called 162 | // to extend diagonals in the forward direction. 163 | func (lcs lcs) append(x, y int) lcs { 164 | if len(lcs) > 0 { 165 | last := &lcs[len(lcs)-1] 166 | // Expand last element if adjoining. 167 | if last.X+last.Len == x && last.Y+last.Len == y { 168 | last.Len++ 169 | return lcs 170 | } 171 | } 172 | 173 | return append(lcs, diag{X: x, Y: y, Len: 1}) 174 | } 175 | 176 | // enforce constraint on d, k 177 | func ok(d, k int) bool { 178 | return d >= 0 && -d <= k && k <= d 179 | } 180 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/diff/lcs/git.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2022 The Go Authors. All rights reserved. 4 | # Use of this source code is governed by a BSD-style 5 | # license that can be found in the LICENSE file. 6 | # 7 | # Creates a zip file containing all numbered versions 8 | # of the commit history of a large source file, for use 9 | # as input data for the tests of the diff algorithm. 10 | # 11 | # Run script from root of the x/tools repo. 12 | 13 | set -eu 14 | 15 | # WARNING: This script will install the latest version of $file 16 | # The largest real source file in the x/tools repo. 17 | # file=internal/golang/completion/completion.go 18 | # file=internal/golang/diagnostics.go 19 | file=internal/protocol/tsprotocol.go 20 | 21 | tmp=$(mktemp -d) 22 | git log $file | 23 | awk '/^commit / {print $2}' | 24 | nl -ba -nrz | 25 | while read n hash; do 26 | git checkout --quiet $hash $file 27 | cp -f $file $tmp/$n 28 | done 29 | (cd $tmp && zip -q - *) > testdata.zip 30 | rm -fr $tmp 31 | git restore --staged $file 32 | git restore $file 33 | echo "Created testdata.zip" 34 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/diff/lcs/labels.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package lcs 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | // For each D, vec[D] has length D+1, 12 | // and the label for (D, k) is stored in vec[D][(D+k)/2]. 13 | type label struct { 14 | vec [][]int 15 | } 16 | 17 | // Temporary checking DO NOT COMMIT true TO PRODUCTION CODE 18 | const debug = false 19 | 20 | // debugging. check that the (d,k) pair is valid 21 | // (that is, -d<=k<=d and d+k even) 22 | func checkDK(D, k int) { 23 | if k >= -D && k <= D && (D+k)%2 == 0 { 24 | return 25 | } 26 | panic(fmt.Sprintf("out of range, d=%d,k=%d", D, k)) 27 | } 28 | 29 | func (t *label) set(D, k, x int) { 30 | if debug { 31 | checkDK(D, k) 32 | } 33 | for len(t.vec) <= D { 34 | t.vec = append(t.vec, nil) 35 | } 36 | if t.vec[D] == nil { 37 | t.vec[D] = make([]int, D+1) 38 | } 39 | t.vec[D][(D+k)/2] = x // known that D+k is even 40 | } 41 | 42 | func (t *label) get(d, k int) int { 43 | if debug { 44 | checkDK(d, k) 45 | } 46 | return int(t.vec[d][(d+k)/2]) 47 | } 48 | 49 | func newtriang(limit int) label { 50 | if limit < 100 { 51 | // Preallocate if limit is not large. 52 | return label{vec: make([][]int, limit)} 53 | } 54 | return label{} 55 | } 56 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/diff/lcs/sequence.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package lcs 6 | 7 | // This file defines the abstract sequence over which the LCS algorithm operates. 8 | 9 | // sequences abstracts a pair of sequences, A and B. 10 | type sequences interface { 11 | lengths() (int, int) // len(A), len(B) 12 | commonPrefixLen(ai, aj, bi, bj int) int // len(commonPrefix(A[ai:aj], B[bi:bj])) 13 | commonSuffixLen(ai, aj, bi, bj int) int // len(commonSuffix(A[ai:aj], B[bi:bj])) 14 | } 15 | 16 | type stringSeqs struct{ a, b string } 17 | 18 | func (s stringSeqs) lengths() (int, int) { return len(s.a), len(s.b) } 19 | func (s stringSeqs) commonPrefixLen(ai, aj, bi, bj int) int { 20 | return commonPrefixLenString(s.a[ai:aj], s.b[bi:bj]) 21 | } 22 | func (s stringSeqs) commonSuffixLen(ai, aj, bi, bj int) int { 23 | return commonSuffixLenString(s.a[ai:aj], s.b[bi:bj]) 24 | } 25 | 26 | // The explicit capacity in s[i:j:j] leads to more efficient code. 27 | 28 | type bytesSeqs struct{ a, b []byte } 29 | 30 | func (s bytesSeqs) lengths() (int, int) { return len(s.a), len(s.b) } 31 | func (s bytesSeqs) commonPrefixLen(ai, aj, bi, bj int) int { 32 | return commonPrefixLenBytes(s.a[ai:aj:aj], s.b[bi:bj:bj]) 33 | } 34 | func (s bytesSeqs) commonSuffixLen(ai, aj, bi, bj int) int { 35 | return commonSuffixLenBytes(s.a[ai:aj:aj], s.b[bi:bj:bj]) 36 | } 37 | 38 | type runesSeqs struct{ a, b []rune } 39 | 40 | func (s runesSeqs) lengths() (int, int) { return len(s.a), len(s.b) } 41 | func (s runesSeqs) commonPrefixLen(ai, aj, bi, bj int) int { 42 | return commonPrefixLenRunes(s.a[ai:aj:aj], s.b[bi:bj:bj]) 43 | } 44 | func (s runesSeqs) commonSuffixLen(ai, aj, bi, bj int) int { 45 | return commonSuffixLenRunes(s.a[ai:aj:aj], s.b[bi:bj:bj]) 46 | } 47 | 48 | // TODO(adonovan): optimize these functions using ideas from: 49 | // - https://go.dev/cl/408116 common.go 50 | // - https://go.dev/cl/421435 xor_generic.go 51 | 52 | // TODO(adonovan): factor using generics when available, 53 | // but measure performance impact. 54 | 55 | // commonPrefixLen* returns the length of the common prefix of a[ai:aj] and b[bi:bj]. 56 | func commonPrefixLenBytes(a, b []byte) int { 57 | n := min(len(a), len(b)) 58 | i := 0 59 | for i < n && a[i] == b[i] { 60 | i++ 61 | } 62 | return i 63 | } 64 | func commonPrefixLenRunes(a, b []rune) int { 65 | n := min(len(a), len(b)) 66 | i := 0 67 | for i < n && a[i] == b[i] { 68 | i++ 69 | } 70 | return i 71 | } 72 | func commonPrefixLenString(a, b string) int { 73 | n := min(len(a), len(b)) 74 | i := 0 75 | for i < n && a[i] == b[i] { 76 | i++ 77 | } 78 | return i 79 | } 80 | 81 | // commonSuffixLen* returns the length of the common suffix of a[ai:aj] and b[bi:bj]. 82 | func commonSuffixLenBytes(a, b []byte) int { 83 | n := min(len(a), len(b)) 84 | i := 0 85 | for i < n && a[len(a)-1-i] == b[len(b)-1-i] { 86 | i++ 87 | } 88 | return i 89 | } 90 | func commonSuffixLenRunes(a, b []rune) int { 91 | n := min(len(a), len(b)) 92 | i := 0 93 | for i < n && a[len(a)-1-i] == b[len(b)-1-i] { 94 | i++ 95 | } 96 | return i 97 | } 98 | func commonSuffixLenString(a, b string) int { 99 | n := min(len(a), len(b)) 100 | i := 0 101 | for i < n && a[len(a)-1-i] == b[len(b)-1-i] { 102 | i++ 103 | } 104 | return i 105 | } 106 | 107 | func min(x, y int) int { 108 | if x < y { 109 | return x 110 | } else { 111 | return y 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/diff/ndiff.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package diff 6 | 7 | import ( 8 | "bytes" 9 | "unicode/utf8" 10 | 11 | "golang.org/x/tools/internal/diff/lcs" 12 | ) 13 | 14 | // Strings computes the differences between two strings. 15 | // The resulting edits respect rune boundaries. 16 | func Strings(before, after string) []Edit { 17 | if before == after { 18 | return nil // common case 19 | } 20 | 21 | if isASCII(before) && isASCII(after) { 22 | // TODO(adonovan): opt: specialize diffASCII for strings. 23 | return diffASCII([]byte(before), []byte(after)) 24 | } 25 | return diffRunes([]rune(before), []rune(after)) 26 | } 27 | 28 | // Bytes computes the differences between two byte slices. 29 | // The resulting edits respect rune boundaries. 30 | func Bytes(before, after []byte) []Edit { 31 | if bytes.Equal(before, after) { 32 | return nil // common case 33 | } 34 | 35 | if isASCII(before) && isASCII(after) { 36 | return diffASCII(before, after) 37 | } 38 | return diffRunes(runes(before), runes(after)) 39 | } 40 | 41 | func diffASCII(before, after []byte) []Edit { 42 | diffs := lcs.DiffBytes(before, after) 43 | 44 | // Convert from LCS diffs. 45 | res := make([]Edit, len(diffs)) 46 | for i, d := range diffs { 47 | res[i] = Edit{d.Start, d.End, string(after[d.ReplStart:d.ReplEnd])} 48 | } 49 | return res 50 | } 51 | 52 | func diffRunes(before, after []rune) []Edit { 53 | diffs := lcs.DiffRunes(before, after) 54 | 55 | // The diffs returned by the lcs package use indexes 56 | // into whatever slice was passed in. 57 | // Convert rune offsets to byte offsets. 58 | res := make([]Edit, len(diffs)) 59 | lastEnd := 0 60 | utf8Len := 0 61 | for i, d := range diffs { 62 | utf8Len += runesLen(before[lastEnd:d.Start]) // text between edits 63 | start := utf8Len 64 | utf8Len += runesLen(before[d.Start:d.End]) // text deleted by this edit 65 | res[i] = Edit{start, utf8Len, string(after[d.ReplStart:d.ReplEnd])} 66 | lastEnd = d.End 67 | } 68 | return res 69 | } 70 | 71 | // runes is like []rune(string(bytes)) without the duplicate allocation. 72 | func runes(bytes []byte) []rune { 73 | n := utf8.RuneCount(bytes) 74 | runes := make([]rune, n) 75 | for i := 0; i < n; i++ { 76 | r, sz := utf8.DecodeRune(bytes) 77 | bytes = bytes[sz:] 78 | runes[i] = r 79 | } 80 | return runes 81 | } 82 | 83 | // runesLen returns the length in bytes of the UTF-8 encoding of runes. 84 | func runesLen(runes []rune) (len int) { 85 | for _, r := range runes { 86 | len += utf8.RuneLen(r) 87 | } 88 | return len 89 | } 90 | 91 | // isASCII reports whether s contains only ASCII. 92 | func isASCII[S string | []byte](s S) bool { 93 | for i := 0; i < len(s); i++ { 94 | if s[i] >= utf8.RuneSelf { 95 | return false 96 | } 97 | } 98 | return true 99 | } 100 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/core/event.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package core provides support for event based telemetry. 6 | package core 7 | 8 | import ( 9 | "fmt" 10 | "time" 11 | 12 | "golang.org/x/tools/internal/event/label" 13 | ) 14 | 15 | // Event holds the information about an event of note that occurred. 16 | type Event struct { 17 | at time.Time 18 | 19 | // As events are often on the stack, storing the first few labels directly 20 | // in the event can avoid an allocation at all for the very common cases of 21 | // simple events. 22 | // The length needs to be large enough to cope with the majority of events 23 | // but no so large as to cause undue stack pressure. 24 | // A log message with two values will use 3 labels (one for each value and 25 | // one for the message itself). 26 | 27 | static [3]label.Label // inline storage for the first few labels 28 | dynamic []label.Label // dynamically sized storage for remaining labels 29 | } 30 | 31 | // eventLabelMap implements label.Map for a the labels of an Event. 32 | type eventLabelMap struct { 33 | event Event 34 | } 35 | 36 | func (ev Event) At() time.Time { return ev.at } 37 | 38 | func (ev Event) Format(f fmt.State, r rune) { 39 | if !ev.at.IsZero() { 40 | fmt.Fprint(f, ev.at.Format("2006/01/02 15:04:05 ")) 41 | } 42 | for index := 0; ev.Valid(index); index++ { 43 | if l := ev.Label(index); l.Valid() { 44 | fmt.Fprintf(f, "\n\t%v", l) 45 | } 46 | } 47 | } 48 | 49 | func (ev Event) Valid(index int) bool { 50 | return index >= 0 && index < len(ev.static)+len(ev.dynamic) 51 | } 52 | 53 | func (ev Event) Label(index int) label.Label { 54 | if index < len(ev.static) { 55 | return ev.static[index] 56 | } 57 | return ev.dynamic[index-len(ev.static)] 58 | } 59 | 60 | func (ev Event) Find(key label.Key) label.Label { 61 | for _, l := range ev.static { 62 | if l.Key() == key { 63 | return l 64 | } 65 | } 66 | for _, l := range ev.dynamic { 67 | if l.Key() == key { 68 | return l 69 | } 70 | } 71 | return label.Label{} 72 | } 73 | 74 | func MakeEvent(static [3]label.Label, labels []label.Label) Event { 75 | return Event{ 76 | static: static, 77 | dynamic: labels, 78 | } 79 | } 80 | 81 | // CloneEvent event returns a copy of the event with the time adjusted to at. 82 | func CloneEvent(ev Event, at time.Time) Event { 83 | ev.at = at 84 | return ev 85 | } 86 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/core/export.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package core 6 | 7 | import ( 8 | "context" 9 | "sync/atomic" 10 | "time" 11 | "unsafe" 12 | 13 | "golang.org/x/tools/internal/event/label" 14 | ) 15 | 16 | // Exporter is a function that handles events. 17 | // It may return a modified context and event. 18 | type Exporter func(context.Context, Event, label.Map) context.Context 19 | 20 | var ( 21 | exporter unsafe.Pointer 22 | ) 23 | 24 | // SetExporter sets the global exporter function that handles all events. 25 | // The exporter is called synchronously from the event call site, so it should 26 | // return quickly so as not to hold up user code. 27 | func SetExporter(e Exporter) { 28 | p := unsafe.Pointer(&e) 29 | if e == nil { 30 | // &e is always valid, and so p is always valid, but for the early abort 31 | // of ProcessEvent to be efficient it needs to make the nil check on the 32 | // pointer without having to dereference it, so we make the nil function 33 | // also a nil pointer 34 | p = nil 35 | } 36 | atomic.StorePointer(&exporter, p) 37 | } 38 | 39 | // deliver is called to deliver an event to the supplied exporter. 40 | // it will fill in the time. 41 | func deliver(ctx context.Context, exporter Exporter, ev Event) context.Context { 42 | // add the current time to the event 43 | ev.at = time.Now() 44 | // hand the event off to the current exporter 45 | return exporter(ctx, ev, ev) 46 | } 47 | 48 | // Export is called to deliver an event to the global exporter if set. 49 | func Export(ctx context.Context, ev Event) context.Context { 50 | // get the global exporter and abort early if there is not one 51 | exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter)) 52 | if exporterPtr == nil { 53 | return ctx 54 | } 55 | return deliver(ctx, *exporterPtr, ev) 56 | } 57 | 58 | // ExportPair is called to deliver a start event to the supplied exporter. 59 | // It also returns a function that will deliver the end event to the same 60 | // exporter. 61 | // It will fill in the time. 62 | func ExportPair(ctx context.Context, begin, end Event) (context.Context, func()) { 63 | // get the global exporter and abort early if there is not one 64 | exporterPtr := (*Exporter)(atomic.LoadPointer(&exporter)) 65 | if exporterPtr == nil { 66 | return ctx, func() {} 67 | } 68 | ctx = deliver(ctx, *exporterPtr, begin) 69 | return ctx, func() { deliver(ctx, *exporterPtr, end) } 70 | } 71 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/core/fast.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package core 6 | 7 | import ( 8 | "context" 9 | 10 | "golang.org/x/tools/internal/event/keys" 11 | "golang.org/x/tools/internal/event/label" 12 | ) 13 | 14 | // Log1 takes a message and one label delivers a log event to the exporter. 15 | // It is a customized version of Print that is faster and does no allocation. 16 | func Log1(ctx context.Context, message string, t1 label.Label) { 17 | Export(ctx, MakeEvent([3]label.Label{ 18 | keys.Msg.Of(message), 19 | t1, 20 | }, nil)) 21 | } 22 | 23 | // Log2 takes a message and two labels and delivers a log event to the exporter. 24 | // It is a customized version of Print that is faster and does no allocation. 25 | func Log2(ctx context.Context, message string, t1 label.Label, t2 label.Label) { 26 | Export(ctx, MakeEvent([3]label.Label{ 27 | keys.Msg.Of(message), 28 | t1, 29 | t2, 30 | }, nil)) 31 | } 32 | 33 | // Metric1 sends a label event to the exporter with the supplied labels. 34 | func Metric1(ctx context.Context, t1 label.Label) context.Context { 35 | return Export(ctx, MakeEvent([3]label.Label{ 36 | keys.Metric.New(), 37 | t1, 38 | }, nil)) 39 | } 40 | 41 | // Metric2 sends a label event to the exporter with the supplied labels. 42 | func Metric2(ctx context.Context, t1, t2 label.Label) context.Context { 43 | return Export(ctx, MakeEvent([3]label.Label{ 44 | keys.Metric.New(), 45 | t1, 46 | t2, 47 | }, nil)) 48 | } 49 | 50 | // Start1 sends a span start event with the supplied label list to the exporter. 51 | // It also returns a function that will end the span, which should normally be 52 | // deferred. 53 | func Start1(ctx context.Context, name string, t1 label.Label) (context.Context, func()) { 54 | return ExportPair(ctx, 55 | MakeEvent([3]label.Label{ 56 | keys.Start.Of(name), 57 | t1, 58 | }, nil), 59 | MakeEvent([3]label.Label{ 60 | keys.End.New(), 61 | }, nil)) 62 | } 63 | 64 | // Start2 sends a span start event with the supplied label list to the exporter. 65 | // It also returns a function that will end the span, which should normally be 66 | // deferred. 67 | func Start2(ctx context.Context, name string, t1, t2 label.Label) (context.Context, func()) { 68 | return ExportPair(ctx, 69 | MakeEvent([3]label.Label{ 70 | keys.Start.Of(name), 71 | t1, 72 | t2, 73 | }, nil), 74 | MakeEvent([3]label.Label{ 75 | keys.End.New(), 76 | }, nil)) 77 | } 78 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package event provides a set of packages that cover the main 6 | // concepts of telemetry in an implementation agnostic way. 7 | package event 8 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/event.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package event 6 | 7 | import ( 8 | "context" 9 | 10 | "golang.org/x/tools/internal/event/core" 11 | "golang.org/x/tools/internal/event/keys" 12 | "golang.org/x/tools/internal/event/label" 13 | ) 14 | 15 | // Exporter is a function that handles events. 16 | // It may return a modified context and event. 17 | type Exporter func(context.Context, core.Event, label.Map) context.Context 18 | 19 | // SetExporter sets the global exporter function that handles all events. 20 | // The exporter is called synchronously from the event call site, so it should 21 | // return quickly so as not to hold up user code. 22 | func SetExporter(e Exporter) { 23 | core.SetExporter(core.Exporter(e)) 24 | } 25 | 26 | // Log takes a message and a label list and combines them into a single event 27 | // before delivering them to the exporter. 28 | func Log(ctx context.Context, message string, labels ...label.Label) { 29 | core.Export(ctx, core.MakeEvent([3]label.Label{ 30 | keys.Msg.Of(message), 31 | }, labels)) 32 | } 33 | 34 | // IsLog returns true if the event was built by the Log function. 35 | // It is intended to be used in exporters to identify the semantics of the 36 | // event when deciding what to do with it. 37 | func IsLog(ev core.Event) bool { 38 | return ev.Label(0).Key() == keys.Msg 39 | } 40 | 41 | // Error takes a message and a label list and combines them into a single event 42 | // before delivering them to the exporter. It captures the error in the 43 | // delivered event. 44 | func Error(ctx context.Context, message string, err error, labels ...label.Label) { 45 | core.Export(ctx, core.MakeEvent([3]label.Label{ 46 | keys.Msg.Of(message), 47 | keys.Err.Of(err), 48 | }, labels)) 49 | } 50 | 51 | // IsError returns true if the event was built by the Error function. 52 | // It is intended to be used in exporters to identify the semantics of the 53 | // event when deciding what to do with it. 54 | func IsError(ev core.Event) bool { 55 | return ev.Label(0).Key() == keys.Msg && 56 | ev.Label(1).Key() == keys.Err 57 | } 58 | 59 | // Metric sends a label event to the exporter with the supplied labels. 60 | func Metric(ctx context.Context, labels ...label.Label) { 61 | core.Export(ctx, core.MakeEvent([3]label.Label{ 62 | keys.Metric.New(), 63 | }, labels)) 64 | } 65 | 66 | // IsMetric returns true if the event was built by the Metric function. 67 | // It is intended to be used in exporters to identify the semantics of the 68 | // event when deciding what to do with it. 69 | func IsMetric(ev core.Event) bool { 70 | return ev.Label(0).Key() == keys.Metric 71 | } 72 | 73 | // Label sends a label event to the exporter with the supplied labels. 74 | func Label(ctx context.Context, labels ...label.Label) context.Context { 75 | return core.Export(ctx, core.MakeEvent([3]label.Label{ 76 | keys.Label.New(), 77 | }, labels)) 78 | } 79 | 80 | // IsLabel returns true if the event was built by the Label function. 81 | // It is intended to be used in exporters to identify the semantics of the 82 | // event when deciding what to do with it. 83 | func IsLabel(ev core.Event) bool { 84 | return ev.Label(0).Key() == keys.Label 85 | } 86 | 87 | // Start sends a span start event with the supplied label list to the exporter. 88 | // It also returns a function that will end the span, which should normally be 89 | // deferred. 90 | func Start(ctx context.Context, name string, labels ...label.Label) (context.Context, func()) { 91 | return core.ExportPair(ctx, 92 | core.MakeEvent([3]label.Label{ 93 | keys.Start.Of(name), 94 | }, labels), 95 | core.MakeEvent([3]label.Label{ 96 | keys.End.New(), 97 | }, nil)) 98 | } 99 | 100 | // IsStart returns true if the event was built by the Start function. 101 | // It is intended to be used in exporters to identify the semantics of the 102 | // event when deciding what to do with it. 103 | func IsStart(ev core.Event) bool { 104 | return ev.Label(0).Key() == keys.Start 105 | } 106 | 107 | // IsEnd returns true if the event was built by the End function. 108 | // It is intended to be used in exporters to identify the semantics of the 109 | // event when deciding what to do with it. 110 | func IsEnd(ev core.Event) bool { 111 | return ev.Label(0).Key() == keys.End 112 | } 113 | 114 | // Detach returns a context without an associated span. 115 | // This allows the creation of spans that are not children of the current span. 116 | func Detach(ctx context.Context) context.Context { 117 | return core.Export(ctx, core.MakeEvent([3]label.Label{ 118 | keys.Detach.New(), 119 | }, nil)) 120 | } 121 | 122 | // IsDetach returns true if the event was built by the Detach function. 123 | // It is intended to be used in exporters to identify the semantics of the 124 | // event when deciding what to do with it. 125 | func IsDetach(ev core.Event) bool { 126 | return ev.Label(0).Key() == keys.Detach 127 | } 128 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/keys/standard.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package keys 6 | 7 | var ( 8 | // Msg is a key used to add message strings to label lists. 9 | Msg = NewString("message", "a readable message") 10 | // Label is a key used to indicate an event adds labels to the context. 11 | Label = NewTag("label", "a label context marker") 12 | // Start is used for things like traces that have a name. 13 | Start = NewString("start", "span start") 14 | // Metric is a key used to indicate an event records metrics. 15 | End = NewTag("end", "a span end marker") 16 | // Metric is a key used to indicate an event records metrics. 17 | Detach = NewTag("detach", "a span detach marker") 18 | // Err is a key used to add error values to label lists. 19 | Err = NewError("error", "an error that occurred") 20 | // Metric is a key used to indicate an event records metrics. 21 | Metric = NewTag("metric", "a metric event marker") 22 | ) 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/event/keys/util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package keys 6 | 7 | import ( 8 | "sort" 9 | "strings" 10 | ) 11 | 12 | // Join returns a canonical join of the keys in S: 13 | // a sorted comma-separated string list. 14 | func Join[S ~[]T, T ~string](s S) string { 15 | strs := make([]string, 0, len(s)) 16 | for _, v := range s { 17 | strs = append(strs, string(v)) 18 | } 19 | sort.Strings(strs) 20 | return strings.Join(strs, ",") 21 | } 22 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/facts/imports.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package facts 6 | 7 | import ( 8 | "go/types" 9 | ) 10 | 11 | // importMap computes the import map for a package by traversing the 12 | // entire exported API each of its imports. 13 | // 14 | // This is a workaround for the fact that we cannot access the map used 15 | // internally by the types.Importer returned by go/importer. The entries 16 | // in this map are the packages and objects that may be relevant to the 17 | // current analysis unit. 18 | // 19 | // Packages in the map that are only indirectly imported may be 20 | // incomplete (!pkg.Complete()). 21 | // 22 | // This function scales very poorly with packages' transitive object 23 | // references, which can be more than a million for each package near 24 | // the top of a large project. (This was a significant contributor to 25 | // #60621.) 26 | // TODO(adonovan): opt: compute this information more efficiently 27 | // by obtaining it from the internals of the gcexportdata decoder. 28 | func importMap(imports []*types.Package) map[string]*types.Package { 29 | objects := make(map[types.Object]bool) 30 | typs := make(map[types.Type]bool) // Named and TypeParam 31 | packages := make(map[string]*types.Package) 32 | 33 | var addObj func(obj types.Object) 34 | var addType func(T types.Type) 35 | 36 | addObj = func(obj types.Object) { 37 | if !objects[obj] { 38 | objects[obj] = true 39 | addType(obj.Type()) 40 | if pkg := obj.Pkg(); pkg != nil { 41 | packages[pkg.Path()] = pkg 42 | } 43 | } 44 | } 45 | 46 | addType = func(T types.Type) { 47 | switch T := T.(type) { 48 | case *types.Alias: 49 | addType(types.Unalias(T)) 50 | case *types.Basic: 51 | // nop 52 | case *types.Named: 53 | // Remove infinite expansions of *types.Named by always looking at the origin. 54 | // Some named types with type parameters [that will not type check] have 55 | // infinite expansions: 56 | // type N[T any] struct { F *N[N[T]] } 57 | // importMap() is called on such types when Analyzer.RunDespiteErrors is true. 58 | T = T.Origin() 59 | if !typs[T] { 60 | typs[T] = true 61 | addObj(T.Obj()) 62 | addType(T.Underlying()) 63 | for i := 0; i < T.NumMethods(); i++ { 64 | addObj(T.Method(i)) 65 | } 66 | if tparams := T.TypeParams(); tparams != nil { 67 | for i := 0; i < tparams.Len(); i++ { 68 | addType(tparams.At(i)) 69 | } 70 | } 71 | if targs := T.TypeArgs(); targs != nil { 72 | for i := 0; i < targs.Len(); i++ { 73 | addType(targs.At(i)) 74 | } 75 | } 76 | } 77 | case *types.Pointer: 78 | addType(T.Elem()) 79 | case *types.Slice: 80 | addType(T.Elem()) 81 | case *types.Array: 82 | addType(T.Elem()) 83 | case *types.Chan: 84 | addType(T.Elem()) 85 | case *types.Map: 86 | addType(T.Key()) 87 | addType(T.Elem()) 88 | case *types.Signature: 89 | addType(T.Params()) 90 | addType(T.Results()) 91 | if tparams := T.TypeParams(); tparams != nil { 92 | for i := 0; i < tparams.Len(); i++ { 93 | addType(tparams.At(i)) 94 | } 95 | } 96 | case *types.Struct: 97 | for i := 0; i < T.NumFields(); i++ { 98 | addObj(T.Field(i)) 99 | } 100 | case *types.Tuple: 101 | for i := 0; i < T.Len(); i++ { 102 | addObj(T.At(i)) 103 | } 104 | case *types.Interface: 105 | for i := 0; i < T.NumMethods(); i++ { 106 | addObj(T.Method(i)) 107 | } 108 | for i := 0; i < T.NumEmbeddeds(); i++ { 109 | addType(T.EmbeddedType(i)) // walk Embedded for implicits 110 | } 111 | case *types.Union: 112 | for i := 0; i < T.Len(); i++ { 113 | addType(T.Term(i).Type()) 114 | } 115 | case *types.TypeParam: 116 | if !typs[T] { 117 | typs[T] = true 118 | addObj(T.Obj()) 119 | addType(T.Constraint()) 120 | } 121 | } 122 | } 123 | 124 | for _, imp := range imports { 125 | packages[imp.Path()] = imp 126 | 127 | scope := imp.Scope() 128 | for _, name := range scope.Names() { 129 | addObj(scope.Lookup(name)) 130 | } 131 | } 132 | 133 | return packages 134 | } 135 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/gcimporter/bimport.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This file contains the remaining vestiges of 6 | // $GOROOT/src/go/internal/gcimporter/bimport.go. 7 | 8 | package gcimporter 9 | 10 | import ( 11 | "fmt" 12 | "go/token" 13 | "go/types" 14 | "sync" 15 | ) 16 | 17 | func errorf(format string, args ...interface{}) { 18 | panic(fmt.Sprintf(format, args...)) 19 | } 20 | 21 | const deltaNewFile = -64 // see cmd/compile/internal/gc/bexport.go 22 | 23 | // Synthesize a token.Pos 24 | type fakeFileSet struct { 25 | fset *token.FileSet 26 | files map[string]*fileInfo 27 | } 28 | 29 | type fileInfo struct { 30 | file *token.File 31 | lastline int 32 | } 33 | 34 | const maxlines = 64 * 1024 35 | 36 | func (s *fakeFileSet) pos(file string, line, column int) token.Pos { 37 | // TODO(mdempsky): Make use of column. 38 | 39 | // Since we don't know the set of needed file positions, we reserve maxlines 40 | // positions per file. We delay calling token.File.SetLines until all 41 | // positions have been calculated (by way of fakeFileSet.setLines), so that 42 | // we can avoid setting unnecessary lines. See also golang/go#46586. 43 | f := s.files[file] 44 | if f == nil { 45 | f = &fileInfo{file: s.fset.AddFile(file, -1, maxlines)} 46 | s.files[file] = f 47 | } 48 | if line > maxlines { 49 | line = 1 50 | } 51 | if line > f.lastline { 52 | f.lastline = line 53 | } 54 | 55 | // Return a fake position assuming that f.file consists only of newlines. 56 | return token.Pos(f.file.Base() + line - 1) 57 | } 58 | 59 | func (s *fakeFileSet) setLines() { 60 | fakeLinesOnce.Do(func() { 61 | fakeLines = make([]int, maxlines) 62 | for i := range fakeLines { 63 | fakeLines[i] = i 64 | } 65 | }) 66 | for _, f := range s.files { 67 | f.file.SetLines(fakeLines[:f.lastline]) 68 | } 69 | } 70 | 71 | var ( 72 | fakeLines []int 73 | fakeLinesOnce sync.Once 74 | ) 75 | 76 | func chanDir(d int) types.ChanDir { 77 | // tag values must match the constants in cmd/compile/internal/gc/go.go 78 | switch d { 79 | case 1 /* Crecv */ : 80 | return types.RecvOnly 81 | case 2 /* Csend */ : 82 | return types.SendOnly 83 | case 3 /* Cboth */ : 84 | return types.SendRecv 85 | default: 86 | errorf("unexpected channel dir %d", d) 87 | return 0 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/gcimporter/exportdata.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This file is a copy of $GOROOT/src/go/internal/gcimporter/exportdata.go. 6 | 7 | // This file implements FindExportData. 8 | 9 | package gcimporter 10 | 11 | import ( 12 | "bufio" 13 | "fmt" 14 | "io" 15 | "strconv" 16 | "strings" 17 | ) 18 | 19 | func readGopackHeader(r *bufio.Reader) (name string, size int64, err error) { 20 | // See $GOROOT/include/ar.h. 21 | hdr := make([]byte, 16+12+6+6+8+10+2) 22 | _, err = io.ReadFull(r, hdr) 23 | if err != nil { 24 | return 25 | } 26 | // leave for debugging 27 | if false { 28 | fmt.Printf("header: %s", hdr) 29 | } 30 | s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10])) 31 | length, err := strconv.Atoi(s) 32 | size = int64(length) 33 | if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { 34 | err = fmt.Errorf("invalid archive header") 35 | return 36 | } 37 | name = strings.TrimSpace(string(hdr[:16])) 38 | return 39 | } 40 | 41 | // FindExportData positions the reader r at the beginning of the 42 | // export data section of an underlying GC-created object/archive 43 | // file by reading from it. The reader must be positioned at the 44 | // start of the file before calling this function. The hdr result 45 | // is the string before the export data, either "$$" or "$$B". 46 | // The size result is the length of the export data in bytes, or -1 if not known. 47 | func FindExportData(r *bufio.Reader) (hdr string, size int64, err error) { 48 | // Read first line to make sure this is an object file. 49 | line, err := r.ReadSlice('\n') 50 | if err != nil { 51 | err = fmt.Errorf("can't find export data (%v)", err) 52 | return 53 | } 54 | 55 | if string(line) == "!\n" { 56 | // Archive file. Scan to __.PKGDEF. 57 | var name string 58 | if name, size, err = readGopackHeader(r); err != nil { 59 | return 60 | } 61 | 62 | // First entry should be __.PKGDEF. 63 | if name != "__.PKGDEF" { 64 | err = fmt.Errorf("go archive is missing __.PKGDEF") 65 | return 66 | } 67 | 68 | // Read first line of __.PKGDEF data, so that line 69 | // is once again the first line of the input. 70 | if line, err = r.ReadSlice('\n'); err != nil { 71 | err = fmt.Errorf("can't find export data (%v)", err) 72 | return 73 | } 74 | size -= int64(len(line)) 75 | } 76 | 77 | // Now at __.PKGDEF in archive or still at beginning of file. 78 | // Either way, line should begin with "go object ". 79 | if !strings.HasPrefix(string(line), "go object ") { 80 | err = fmt.Errorf("not a Go object file") 81 | return 82 | } 83 | 84 | // Skip over object header to export data. 85 | // Begins after first line starting with $$. 86 | for line[0] != '$' { 87 | if line, err = r.ReadSlice('\n'); err != nil { 88 | err = fmt.Errorf("can't find export data (%v)", err) 89 | return 90 | } 91 | size -= int64(len(line)) 92 | } 93 | hdr = string(line) 94 | if size < 0 { 95 | size = -1 96 | } 97 | 98 | return 99 | } 100 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/gcimporter/iimport_go122.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build go1.22 && !go1.24 6 | 7 | package gcimporter 8 | 9 | import ( 10 | "go/token" 11 | "go/types" 12 | "unsafe" 13 | ) 14 | 15 | // TODO(rfindley): delete this workaround once go1.24 is assured. 16 | 17 | func init() { 18 | // Update markBlack so that it correctly sets the color 19 | // of imported TypeNames. 20 | // 21 | // See the doc comment for markBlack for details. 22 | 23 | type color uint32 24 | const ( 25 | white color = iota 26 | black 27 | grey 28 | ) 29 | type object struct { 30 | _ *types.Scope 31 | _ token.Pos 32 | _ *types.Package 33 | _ string 34 | _ types.Type 35 | _ uint32 36 | color_ color 37 | _ token.Pos 38 | } 39 | type typeName struct { 40 | object 41 | } 42 | 43 | // If the size of types.TypeName changes, this will fail to compile. 44 | const delta = int64(unsafe.Sizeof(typeName{})) - int64(unsafe.Sizeof(types.TypeName{})) 45 | var _ [-delta * delta]int 46 | 47 | markBlack = func(obj *types.TypeName) { 48 | type uP = unsafe.Pointer 49 | var ptr *typeName 50 | *(*uP)(uP(&ptr)) = uP(obj) 51 | ptr.color_ = black 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/gcimporter/predeclared.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package gcimporter 6 | 7 | import ( 8 | "go/types" 9 | "sync" 10 | ) 11 | 12 | // predecl is a cache for the predeclared types in types.Universe. 13 | // 14 | // Cache a distinct result based on the runtime value of any. 15 | // The pointer value of the any type varies based on GODEBUG settings. 16 | var predeclMu sync.Mutex 17 | var predecl map[types.Type][]types.Type 18 | 19 | func predeclared() []types.Type { 20 | anyt := types.Universe.Lookup("any").Type() 21 | 22 | predeclMu.Lock() 23 | defer predeclMu.Unlock() 24 | 25 | if pre, ok := predecl[anyt]; ok { 26 | return pre 27 | } 28 | 29 | if predecl == nil { 30 | predecl = make(map[types.Type][]types.Type) 31 | } 32 | 33 | decls := []types.Type{ // basic types 34 | types.Typ[types.Bool], 35 | types.Typ[types.Int], 36 | types.Typ[types.Int8], 37 | types.Typ[types.Int16], 38 | types.Typ[types.Int32], 39 | types.Typ[types.Int64], 40 | types.Typ[types.Uint], 41 | types.Typ[types.Uint8], 42 | types.Typ[types.Uint16], 43 | types.Typ[types.Uint32], 44 | types.Typ[types.Uint64], 45 | types.Typ[types.Uintptr], 46 | types.Typ[types.Float32], 47 | types.Typ[types.Float64], 48 | types.Typ[types.Complex64], 49 | types.Typ[types.Complex128], 50 | types.Typ[types.String], 51 | 52 | // basic type aliases 53 | types.Universe.Lookup("byte").Type(), 54 | types.Universe.Lookup("rune").Type(), 55 | 56 | // error 57 | types.Universe.Lookup("error").Type(), 58 | 59 | // untyped types 60 | types.Typ[types.UntypedBool], 61 | types.Typ[types.UntypedInt], 62 | types.Typ[types.UntypedRune], 63 | types.Typ[types.UntypedFloat], 64 | types.Typ[types.UntypedComplex], 65 | types.Typ[types.UntypedString], 66 | types.Typ[types.UntypedNil], 67 | 68 | // package unsafe 69 | types.Typ[types.UnsafePointer], 70 | 71 | // invalid type 72 | types.Typ[types.Invalid], // only appears in packages with errors 73 | 74 | // used internally by gc; never used by this package or in .a files 75 | anyType{}, 76 | 77 | // comparable 78 | types.Universe.Lookup("comparable").Type(), 79 | 80 | // any 81 | anyt, 82 | } 83 | 84 | predecl[anyt] = decls 85 | return decls 86 | } 87 | 88 | type anyType struct{} 89 | 90 | func (t anyType) Underlying() types.Type { return t } 91 | func (t anyType) String() string { return "any" } 92 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/gocommand/vendor.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package gocommand 6 | 7 | import ( 8 | "bytes" 9 | "context" 10 | "fmt" 11 | "os" 12 | "path/filepath" 13 | "regexp" 14 | "strings" 15 | "time" 16 | 17 | "golang.org/x/mod/semver" 18 | ) 19 | 20 | // ModuleJSON holds information about a module. 21 | type ModuleJSON struct { 22 | Path string // module path 23 | Version string // module version 24 | Versions []string // available module versions (with -versions) 25 | Replace *ModuleJSON // replaced by this module 26 | Time *time.Time // time version was created 27 | Update *ModuleJSON // available update, if any (with -u) 28 | Main bool // is this the main module? 29 | Indirect bool // is this module only an indirect dependency of main module? 30 | Dir string // directory holding files for this module, if any 31 | GoMod string // path to go.mod file used when loading this module, if any 32 | GoVersion string // go version used in module 33 | } 34 | 35 | var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`) 36 | 37 | // VendorEnabled reports whether vendoring is enabled. It takes a *Runner to execute Go commands 38 | // with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields, 39 | // of which only Verb and Args are modified to run the appropriate Go command. 40 | // Inspired by setDefaultBuildMod in modload/init.go 41 | func VendorEnabled(ctx context.Context, inv Invocation, r *Runner) (bool, *ModuleJSON, error) { 42 | mainMod, go114, err := getMainModuleAnd114(ctx, inv, r) 43 | if err != nil { 44 | return false, nil, err 45 | } 46 | 47 | // We check the GOFLAGS to see if there is anything overridden or not. 48 | inv.Verb = "env" 49 | inv.Args = []string{"GOFLAGS"} 50 | stdout, err := r.Run(ctx, inv) 51 | if err != nil { 52 | return false, nil, err 53 | } 54 | goflags := string(bytes.TrimSpace(stdout.Bytes())) 55 | matches := modFlagRegexp.FindStringSubmatch(goflags) 56 | var modFlag string 57 | if len(matches) != 0 { 58 | modFlag = matches[1] 59 | } 60 | // Don't override an explicit '-mod=' argument. 61 | if modFlag == "vendor" { 62 | return true, mainMod, nil 63 | } else if modFlag != "" { 64 | return false, nil, nil 65 | } 66 | if mainMod == nil || !go114 { 67 | return false, nil, nil 68 | } 69 | // Check 1.14's automatic vendor mode. 70 | if fi, err := os.Stat(filepath.Join(mainMod.Dir, "vendor")); err == nil && fi.IsDir() { 71 | if mainMod.GoVersion != "" && semver.Compare("v"+mainMod.GoVersion, "v1.14") >= 0 { 72 | // The Go version is at least 1.14, and a vendor directory exists. 73 | // Set -mod=vendor by default. 74 | return true, mainMod, nil 75 | } 76 | } 77 | return false, nil, nil 78 | } 79 | 80 | // getMainModuleAnd114 gets one of the main modules' information and whether the 81 | // go command in use is 1.14+. This is the information needed to figure out 82 | // if vendoring should be enabled. 83 | func getMainModuleAnd114(ctx context.Context, inv Invocation, r *Runner) (*ModuleJSON, bool, error) { 84 | const format = `{{.Path}} 85 | {{.Dir}} 86 | {{.GoMod}} 87 | {{.GoVersion}} 88 | {{range context.ReleaseTags}}{{if eq . "go1.14"}}{{.}}{{end}}{{end}} 89 | ` 90 | inv.Verb = "list" 91 | inv.Args = []string{"-m", "-f", format} 92 | stdout, err := r.Run(ctx, inv) 93 | if err != nil { 94 | return nil, false, err 95 | } 96 | 97 | lines := strings.Split(stdout.String(), "\n") 98 | if len(lines) < 5 { 99 | return nil, false, fmt.Errorf("unexpected stdout: %q", stdout.String()) 100 | } 101 | mod := &ModuleJSON{ 102 | Path: lines[0], 103 | Dir: lines[1], 104 | GoMod: lines[2], 105 | GoVersion: lines[3], 106 | Main: true, 107 | } 108 | return mod, lines[4] == "go1.14", nil 109 | } 110 | 111 | // WorkspaceVendorEnabled reports whether workspace vendoring is enabled. It takes a *Runner to execute Go commands 112 | // with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields, 113 | // of which only Verb and Args are modified to run the appropriate Go command. 114 | // Inspired by setDefaultBuildMod in modload/init.go 115 | func WorkspaceVendorEnabled(ctx context.Context, inv Invocation, r *Runner) (bool, []*ModuleJSON, error) { 116 | inv.Verb = "env" 117 | inv.Args = []string{"GOWORK"} 118 | stdout, err := r.Run(ctx, inv) 119 | if err != nil { 120 | return false, nil, err 121 | } 122 | goWork := string(bytes.TrimSpace(stdout.Bytes())) 123 | if fi, err := os.Stat(filepath.Join(filepath.Dir(goWork), "vendor")); err == nil && fi.IsDir() { 124 | mainMods, err := getWorkspaceMainModules(ctx, inv, r) 125 | if err != nil { 126 | return false, nil, err 127 | } 128 | return true, mainMods, nil 129 | } 130 | return false, nil, nil 131 | } 132 | 133 | // getWorkspaceMainModules gets the main modules' information. 134 | // This is the information needed to figure out if vendoring should be enabled. 135 | func getWorkspaceMainModules(ctx context.Context, inv Invocation, r *Runner) ([]*ModuleJSON, error) { 136 | const format = `{{.Path}} 137 | {{.Dir}} 138 | {{.GoMod}} 139 | {{.GoVersion}} 140 | ` 141 | inv.Verb = "list" 142 | inv.Args = []string{"-m", "-f", format} 143 | stdout, err := r.Run(ctx, inv) 144 | if err != nil { 145 | return nil, err 146 | } 147 | 148 | lines := strings.Split(strings.TrimSuffix(stdout.String(), "\n"), "\n") 149 | if len(lines) < 4 { 150 | return nil, fmt.Errorf("unexpected stdout: %q", stdout.String()) 151 | } 152 | mods := make([]*ModuleJSON, 0, len(lines)/4) 153 | for i := 0; i < len(lines); i += 4 { 154 | mods = append(mods, &ModuleJSON{ 155 | Path: lines[i], 156 | Dir: lines[i+1], 157 | GoMod: lines[i+2], 158 | GoVersion: lines[i+3], 159 | Main: true, 160 | }) 161 | } 162 | return mods, nil 163 | } 164 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/gocommand/version.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package gocommand 6 | 7 | import ( 8 | "context" 9 | "fmt" 10 | "regexp" 11 | "strings" 12 | ) 13 | 14 | // GoVersion reports the minor version number of the highest release 15 | // tag built into the go command on the PATH. 16 | // 17 | // Note that this may be higher than the version of the go tool used 18 | // to build this application, and thus the versions of the standard 19 | // go/{scanner,parser,ast,types} packages that are linked into it. 20 | // In that case, callers should either downgrade to the version of 21 | // go used to build the application, or report an error that the 22 | // application is too old to use the go command on the PATH. 23 | func GoVersion(ctx context.Context, inv Invocation, r *Runner) (int, error) { 24 | inv.Verb = "list" 25 | inv.Args = []string{"-e", "-f", `{{context.ReleaseTags}}`, `--`, `unsafe`} 26 | inv.BuildFlags = nil // This is not a build command. 27 | inv.ModFlag = "" 28 | inv.ModFile = "" 29 | inv.Env = append(inv.Env[:len(inv.Env):len(inv.Env)], "GO111MODULE=off") 30 | 31 | stdoutBytes, err := r.Run(ctx, inv) 32 | if err != nil { 33 | return 0, err 34 | } 35 | stdout := stdoutBytes.String() 36 | if len(stdout) < 3 { 37 | return 0, fmt.Errorf("bad ReleaseTags output: %q", stdout) 38 | } 39 | // Split up "[go1.1 go1.15]" and return highest go1.X value. 40 | tags := strings.Fields(stdout[1 : len(stdout)-2]) 41 | for i := len(tags) - 1; i >= 0; i-- { 42 | var version int 43 | if _, err := fmt.Sscanf(tags[i], "go1.%d", &version); err != nil { 44 | continue 45 | } 46 | return version, nil 47 | } 48 | return 0, fmt.Errorf("no parseable ReleaseTags in %v", tags) 49 | } 50 | 51 | // GoVersionOutput returns the complete output of the go version command. 52 | func GoVersionOutput(ctx context.Context, inv Invocation, r *Runner) (string, error) { 53 | inv.Verb = "version" 54 | goVersion, err := r.Run(ctx, inv) 55 | if err != nil { 56 | return "", err 57 | } 58 | return goVersion.String(), nil 59 | } 60 | 61 | // ParseGoVersionOutput extracts the Go version string 62 | // from the output of the "go version" command. 63 | // Given an unrecognized form, it returns an empty string. 64 | func ParseGoVersionOutput(data string) string { 65 | re := regexp.MustCompile(`^go version (go\S+|devel \S+)`) 66 | m := re.FindStringSubmatch(data) 67 | if len(m) != 2 { 68 | return "" // unrecognized version 69 | } 70 | return m[1] 71 | } 72 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/goroot/importcfg.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package goroot is a copy of package internal/goroot 6 | // in the main GO repot. It provides a utility to produce 7 | // an importcfg and import path to package file map mapping 8 | // standard library packages to the locations of their export 9 | // data files. 10 | package goroot 11 | 12 | import ( 13 | "bytes" 14 | "fmt" 15 | "os/exec" 16 | "strings" 17 | "sync" 18 | ) 19 | 20 | // Importcfg returns an importcfg file to be passed to the 21 | // Go compiler that contains the cached paths for the .a files for the 22 | // standard library. 23 | func Importcfg() (string, error) { 24 | var icfg bytes.Buffer 25 | 26 | m, err := PkgfileMap() 27 | if err != nil { 28 | return "", err 29 | } 30 | fmt.Fprintf(&icfg, "# import config") 31 | for importPath, export := range m { 32 | fmt.Fprintf(&icfg, "\npackagefile %s=%s", importPath, export) 33 | } 34 | s := icfg.String() 35 | return s, nil 36 | } 37 | 38 | var ( 39 | stdlibPkgfileMap map[string]string 40 | stdlibPkgfileErr error 41 | once sync.Once 42 | ) 43 | 44 | // PkgfileMap returns a map of package paths to the location on disk 45 | // of the .a file for the package. 46 | // The caller must not modify the map. 47 | func PkgfileMap() (map[string]string, error) { 48 | once.Do(func() { 49 | m := make(map[string]string) 50 | output, err := exec.Command("go", "list", "-export", "-e", "-f", "{{.ImportPath}} {{.Export}}", "std", "cmd").Output() 51 | if err != nil { 52 | stdlibPkgfileErr = err 53 | } 54 | for _, line := range strings.Split(string(output), "\n") { 55 | if line == "" { 56 | continue 57 | } 58 | sp := strings.SplitN(line, " ", 2) 59 | if len(sp) != 2 { 60 | err = fmt.Errorf("determining pkgfile map: invalid line in go list output: %q", line) 61 | return 62 | } 63 | importPath, export := sp[0], sp[1] 64 | if export != "" { 65 | m[importPath] = export 66 | } 67 | } 68 | stdlibPkgfileMap = m 69 | }) 70 | return stdlibPkgfileMap, stdlibPkgfileErr 71 | } 72 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/packagesinternal/packages.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package packagesinternal exposes internal-only fields from go/packages. 6 | package packagesinternal 7 | 8 | var GetForTest = func(p interface{}) string { return "" } 9 | var GetDepsErrors = func(p interface{}) []*PackageError { return nil } 10 | 11 | type PackageError struct { 12 | ImportStack []string // shortest path from package named on command line to this one 13 | Pos string // position of error (if present, file:line:col) 14 | Err string // the error itself 15 | } 16 | 17 | var TypecheckCgo int 18 | var DepsErrors int // must be set as a LoadMode to call GetDepsErrors 19 | var ForTest int // must be set as a LoadMode to call GetForTest 20 | 21 | var SetModFlag = func(config interface{}, value string) {} 22 | var SetModFile = func(config interface{}, value string) {} 23 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/codes.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkgbits 6 | 7 | // A Code is an enum value that can be encoded into bitstreams. 8 | // 9 | // Code types are preferable for enum types, because they allow 10 | // Decoder to detect desyncs. 11 | type Code interface { 12 | // Marker returns the SyncMarker for the Code's dynamic type. 13 | Marker() SyncMarker 14 | 15 | // Value returns the Code's ordinal value. 16 | Value() int 17 | } 18 | 19 | // A CodeVal distinguishes among go/constant.Value encodings. 20 | type CodeVal int 21 | 22 | func (c CodeVal) Marker() SyncMarker { return SyncVal } 23 | func (c CodeVal) Value() int { return int(c) } 24 | 25 | // Note: These values are public and cannot be changed without 26 | // updating the go/types importers. 27 | 28 | const ( 29 | ValBool CodeVal = iota 30 | ValString 31 | ValInt64 32 | ValBigInt 33 | ValBigRat 34 | ValBigFloat 35 | ) 36 | 37 | // A CodeType distinguishes among go/types.Type encodings. 38 | type CodeType int 39 | 40 | func (c CodeType) Marker() SyncMarker { return SyncType } 41 | func (c CodeType) Value() int { return int(c) } 42 | 43 | // Note: These values are public and cannot be changed without 44 | // updating the go/types importers. 45 | 46 | const ( 47 | TypeBasic CodeType = iota 48 | TypeNamed 49 | TypePointer 50 | TypeSlice 51 | TypeArray 52 | TypeChan 53 | TypeMap 54 | TypeSignature 55 | TypeStruct 56 | TypeInterface 57 | TypeUnion 58 | TypeTypeParam 59 | ) 60 | 61 | // A CodeObj distinguishes among go/types.Object encodings. 62 | type CodeObj int 63 | 64 | func (c CodeObj) Marker() SyncMarker { return SyncCodeObj } 65 | func (c CodeObj) Value() int { return int(c) } 66 | 67 | // Note: These values are public and cannot be changed without 68 | // updating the go/types importers. 69 | 70 | const ( 71 | ObjAlias CodeObj = iota 72 | ObjConst 73 | ObjType 74 | ObjFunc 75 | ObjVar 76 | ObjStub 77 | ) 78 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package pkgbits implements low-level coding abstractions for 6 | // Unified IR's export data format. 7 | // 8 | // At a low-level, a package is a collection of bitstream elements. 9 | // Each element has a "kind" and a dense, non-negative index. 10 | // Elements can be randomly accessed given their kind and index. 11 | // 12 | // Individual elements are sequences of variable-length values (e.g., 13 | // integers, booleans, strings, go/constant values, cross-references 14 | // to other elements). Package pkgbits provides APIs for encoding and 15 | // decoding these low-level values, but the details of mapping 16 | // higher-level Go constructs into elements is left to higher-level 17 | // abstractions. 18 | // 19 | // Elements may cross-reference each other with "relocations." For 20 | // example, an element representing a pointer type has a relocation 21 | // referring to the element type. 22 | // 23 | // Go constructs may be composed as a constellation of multiple 24 | // elements. For example, a declared function may have one element to 25 | // describe the object (e.g., its name, type, position), and a 26 | // separate element to describe its function body. This allows readers 27 | // some flexibility in efficiently seeking or re-reading data (e.g., 28 | // inlining requires re-reading the function body for each inlined 29 | // call, without needing to re-read the object-level details). 30 | // 31 | // This is a copy of internal/pkgbits in the Go implementation. 32 | package pkgbits 33 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/flags.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkgbits 6 | 7 | const ( 8 | flagSyncMarkers = 1 << iota // file format contains sync markers 9 | ) 10 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/reloc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkgbits 6 | 7 | // A RelocKind indicates a particular section within a unified IR export. 8 | type RelocKind int32 9 | 10 | // An Index represents a bitstream element index within a particular 11 | // section. 12 | type Index int32 13 | 14 | // A relocEnt (relocation entry) is an entry in an element's local 15 | // reference table. 16 | // 17 | // TODO(mdempsky): Rename this too. 18 | type RelocEnt struct { 19 | Kind RelocKind 20 | Idx Index 21 | } 22 | 23 | // Reserved indices within the meta relocation section. 24 | const ( 25 | PublicRootIdx Index = 0 26 | PrivateRootIdx Index = 1 27 | ) 28 | 29 | const ( 30 | RelocString RelocKind = iota 31 | RelocMeta 32 | RelocPosBase 33 | RelocPkg 34 | RelocName 35 | RelocType 36 | RelocObj 37 | RelocObjExt 38 | RelocObjDict 39 | RelocBody 40 | 41 | numRelocs = iota 42 | ) 43 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/support.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkgbits 6 | 7 | import "fmt" 8 | 9 | func assert(b bool) { 10 | if !b { 11 | panic("assertion failed") 12 | } 13 | } 14 | 15 | func panicf(format string, args ...any) { 16 | panic(fmt.Errorf(format, args...)) 17 | } 18 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/sync.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkgbits 6 | 7 | import ( 8 | "fmt" 9 | "runtime" 10 | "strings" 11 | ) 12 | 13 | // fmtFrames formats a backtrace for reporting reader/writer desyncs. 14 | func fmtFrames(pcs ...uintptr) []string { 15 | res := make([]string, 0, len(pcs)) 16 | walkFrames(pcs, func(file string, line int, name string, offset uintptr) { 17 | // Trim package from function name. It's just redundant noise. 18 | name = strings.TrimPrefix(name, "cmd/compile/internal/noder.") 19 | 20 | res = append(res, fmt.Sprintf("%s:%v: %s +0x%v", file, line, name, offset)) 21 | }) 22 | return res 23 | } 24 | 25 | type frameVisitor func(file string, line int, name string, offset uintptr) 26 | 27 | // walkFrames calls visit for each call frame represented by pcs. 28 | // 29 | // pcs should be a slice of PCs, as returned by runtime.Callers. 30 | func walkFrames(pcs []uintptr, visit frameVisitor) { 31 | if len(pcs) == 0 { 32 | return 33 | } 34 | 35 | frames := runtime.CallersFrames(pcs) 36 | for { 37 | frame, more := frames.Next() 38 | visit(frame.File, frame.Line, frame.Function, frame.PC-frame.Entry) 39 | if !more { 40 | return 41 | } 42 | } 43 | } 44 | 45 | // SyncMarker is an enum type that represents markers that may be 46 | // written to export data to ensure the reader and writer stay 47 | // synchronized. 48 | type SyncMarker int 49 | 50 | //go:generate stringer -type=SyncMarker -trimprefix=Sync 51 | 52 | const ( 53 | _ SyncMarker = iota 54 | 55 | // Public markers (known to go/types importers). 56 | 57 | // Low-level coding markers. 58 | SyncEOF 59 | SyncBool 60 | SyncInt64 61 | SyncUint64 62 | SyncString 63 | SyncValue 64 | SyncVal 65 | SyncRelocs 66 | SyncReloc 67 | SyncUseReloc 68 | 69 | // Higher-level object and type markers. 70 | SyncPublic 71 | SyncPos 72 | SyncPosBase 73 | SyncObject 74 | SyncObject1 75 | SyncPkg 76 | SyncPkgDef 77 | SyncMethod 78 | SyncType 79 | SyncTypeIdx 80 | SyncTypeParamNames 81 | SyncSignature 82 | SyncParams 83 | SyncParam 84 | SyncCodeObj 85 | SyncSym 86 | SyncLocalIdent 87 | SyncSelector 88 | 89 | // Private markers (only known to cmd/compile). 90 | SyncPrivate 91 | 92 | SyncFuncExt 93 | SyncVarExt 94 | SyncTypeExt 95 | SyncPragma 96 | 97 | SyncExprList 98 | SyncExprs 99 | SyncExpr 100 | SyncExprType 101 | SyncAssign 102 | SyncOp 103 | SyncFuncLit 104 | SyncCompLit 105 | 106 | SyncDecl 107 | SyncFuncBody 108 | SyncOpenScope 109 | SyncCloseScope 110 | SyncCloseAnotherScope 111 | SyncDeclNames 112 | SyncDeclName 113 | 114 | SyncStmts 115 | SyncBlockStmt 116 | SyncIfStmt 117 | SyncForStmt 118 | SyncSwitchStmt 119 | SyncRangeStmt 120 | SyncCaseClause 121 | SyncCommClause 122 | SyncSelectStmt 123 | SyncDecls 124 | SyncLabeledStmt 125 | SyncUseObjLocal 126 | SyncAddLocal 127 | SyncLinkname 128 | SyncStmt1 129 | SyncStmtsEnd 130 | SyncLabel 131 | SyncOptLabel 132 | 133 | SyncMultiExpr 134 | SyncRType 135 | SyncConvRTTI 136 | ) 137 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/syncmarker_string.go: -------------------------------------------------------------------------------- 1 | // Code generated by "stringer -type=SyncMarker -trimprefix=Sync"; DO NOT EDIT. 2 | 3 | package pkgbits 4 | 5 | import "strconv" 6 | 7 | func _() { 8 | // An "invalid array index" compiler error signifies that the constant values have changed. 9 | // Re-run the stringer command to generate them again. 10 | var x [1]struct{} 11 | _ = x[SyncEOF-1] 12 | _ = x[SyncBool-2] 13 | _ = x[SyncInt64-3] 14 | _ = x[SyncUint64-4] 15 | _ = x[SyncString-5] 16 | _ = x[SyncValue-6] 17 | _ = x[SyncVal-7] 18 | _ = x[SyncRelocs-8] 19 | _ = x[SyncReloc-9] 20 | _ = x[SyncUseReloc-10] 21 | _ = x[SyncPublic-11] 22 | _ = x[SyncPos-12] 23 | _ = x[SyncPosBase-13] 24 | _ = x[SyncObject-14] 25 | _ = x[SyncObject1-15] 26 | _ = x[SyncPkg-16] 27 | _ = x[SyncPkgDef-17] 28 | _ = x[SyncMethod-18] 29 | _ = x[SyncType-19] 30 | _ = x[SyncTypeIdx-20] 31 | _ = x[SyncTypeParamNames-21] 32 | _ = x[SyncSignature-22] 33 | _ = x[SyncParams-23] 34 | _ = x[SyncParam-24] 35 | _ = x[SyncCodeObj-25] 36 | _ = x[SyncSym-26] 37 | _ = x[SyncLocalIdent-27] 38 | _ = x[SyncSelector-28] 39 | _ = x[SyncPrivate-29] 40 | _ = x[SyncFuncExt-30] 41 | _ = x[SyncVarExt-31] 42 | _ = x[SyncTypeExt-32] 43 | _ = x[SyncPragma-33] 44 | _ = x[SyncExprList-34] 45 | _ = x[SyncExprs-35] 46 | _ = x[SyncExpr-36] 47 | _ = x[SyncExprType-37] 48 | _ = x[SyncAssign-38] 49 | _ = x[SyncOp-39] 50 | _ = x[SyncFuncLit-40] 51 | _ = x[SyncCompLit-41] 52 | _ = x[SyncDecl-42] 53 | _ = x[SyncFuncBody-43] 54 | _ = x[SyncOpenScope-44] 55 | _ = x[SyncCloseScope-45] 56 | _ = x[SyncCloseAnotherScope-46] 57 | _ = x[SyncDeclNames-47] 58 | _ = x[SyncDeclName-48] 59 | _ = x[SyncStmts-49] 60 | _ = x[SyncBlockStmt-50] 61 | _ = x[SyncIfStmt-51] 62 | _ = x[SyncForStmt-52] 63 | _ = x[SyncSwitchStmt-53] 64 | _ = x[SyncRangeStmt-54] 65 | _ = x[SyncCaseClause-55] 66 | _ = x[SyncCommClause-56] 67 | _ = x[SyncSelectStmt-57] 68 | _ = x[SyncDecls-58] 69 | _ = x[SyncLabeledStmt-59] 70 | _ = x[SyncUseObjLocal-60] 71 | _ = x[SyncAddLocal-61] 72 | _ = x[SyncLinkname-62] 73 | _ = x[SyncStmt1-63] 74 | _ = x[SyncStmtsEnd-64] 75 | _ = x[SyncLabel-65] 76 | _ = x[SyncOptLabel-66] 77 | _ = x[SyncMultiExpr-67] 78 | _ = x[SyncRType-68] 79 | _ = x[SyncConvRTTI-69] 80 | } 81 | 82 | const _SyncMarker_name = "EOFBoolInt64Uint64StringValueValRelocsRelocUseRelocPublicPosPosBaseObjectObject1PkgPkgDefMethodTypeTypeIdxTypeParamNamesSignatureParamsParamCodeObjSymLocalIdentSelectorPrivateFuncExtVarExtTypeExtPragmaExprListExprsExprExprTypeAssignOpFuncLitCompLitDeclFuncBodyOpenScopeCloseScopeCloseAnotherScopeDeclNamesDeclNameStmtsBlockStmtIfStmtForStmtSwitchStmtRangeStmtCaseClauseCommClauseSelectStmtDeclsLabeledStmtUseObjLocalAddLocalLinknameStmt1StmtsEndLabelOptLabelMultiExprRTypeConvRTTI" 83 | 84 | var _SyncMarker_index = [...]uint16{0, 3, 7, 12, 18, 24, 29, 32, 38, 43, 51, 57, 60, 67, 73, 80, 83, 89, 95, 99, 106, 120, 129, 135, 140, 147, 150, 160, 168, 175, 182, 188, 195, 201, 209, 214, 218, 226, 232, 234, 241, 248, 252, 260, 269, 279, 296, 305, 313, 318, 327, 333, 340, 350, 359, 369, 379, 389, 394, 405, 416, 424, 432, 437, 445, 450, 458, 467, 472, 480} 85 | 86 | func (i SyncMarker) String() string { 87 | i -= 1 88 | if i < 0 || i >= SyncMarker(len(_SyncMarker_index)-1) { 89 | return "SyncMarker(" + strconv.FormatInt(int64(i+1), 10) + ")" 90 | } 91 | return _SyncMarker_name[_SyncMarker_index[i]:_SyncMarker_index[i+1]] 92 | } 93 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/pkgbits/version.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package pkgbits 6 | 7 | // Version indicates a version of a unified IR bitstream. 8 | // Each Version indicates the addition, removal, or change of 9 | // new data in the bitstream. 10 | // 11 | // These are serialized to disk and the interpretation remains fixed. 12 | type Version uint32 13 | 14 | const ( 15 | // V0: initial prototype. 16 | // 17 | // All data that is not assigned a Field is in version V0 18 | // and has not been deprecated. 19 | V0 Version = iota 20 | 21 | // V1: adds the Flags uint32 word 22 | V1 23 | 24 | // V2: removes unused legacy fields and supports type parameters for aliases. 25 | // - remove the legacy "has init" bool from the public root 26 | // - remove obj's "derived func instance" bool 27 | // - add a TypeParamNames field to ObjAlias 28 | // - remove derived info "needed" bool 29 | V2 30 | 31 | numVersions = iota 32 | ) 33 | 34 | // Field denotes a unit of data in the serialized unified IR bitstream. 35 | // It is conceptually a like field in a structure. 36 | // 37 | // We only really need Fields when the data may or may not be present 38 | // in a stream based on the Version of the bitstream. 39 | // 40 | // Unlike much of pkgbits, Fields are not serialized and 41 | // can change values as needed. 42 | type Field int 43 | 44 | const ( 45 | // Flags in a uint32 in the header of a bitstream 46 | // that is used to indicate whether optional features are enabled. 47 | Flags Field = iota 48 | 49 | // Deprecated: HasInit was a bool indicating whether a package 50 | // has any init functions. 51 | HasInit 52 | 53 | // Deprecated: DerivedFuncInstance was a bool indicating 54 | // whether an object was a function instance. 55 | DerivedFuncInstance 56 | 57 | // ObjAlias has a list of TypeParamNames. 58 | AliasTypeParamNames 59 | 60 | // Deprecated: DerivedInfoNeeded was a bool indicating 61 | // whether a type was a derived type. 62 | DerivedInfoNeeded 63 | 64 | numFields = iota 65 | ) 66 | 67 | // introduced is the version a field was added. 68 | var introduced = [numFields]Version{ 69 | Flags: V1, 70 | AliasTypeParamNames: V2, 71 | } 72 | 73 | // removed is the version a field was removed in or 0 for fields 74 | // that have not yet been deprecated. 75 | // (So removed[f]-1 is the last version it is included in.) 76 | var removed = [numFields]Version{ 77 | HasInit: V2, 78 | DerivedFuncInstance: V2, 79 | DerivedInfoNeeded: V2, 80 | } 81 | 82 | // Has reports whether field f is present in a bitstream at version v. 83 | func (v Version) Has(f Field) bool { 84 | return introduced[f] <= v && (v < removed[f] || removed[f] == V0) 85 | } 86 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/gopls_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package robustio 6 | 7 | import "syscall" 8 | 9 | // The robustio package is copied from cmd/go/internal/robustio, a package used 10 | // by the go command to retry known flaky operations on certain operating systems. 11 | 12 | //go:generate go run copyfiles.go 13 | 14 | // Since the gopls module cannot access internal/syscall/windows, copy a 15 | // necessary constant. 16 | const ERROR_SHARING_VIOLATION syscall.Errno = 32 17 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package robustio wraps I/O functions that are prone to failure on Windows, 6 | // transparently retrying errors up to an arbitrary timeout. 7 | // 8 | // Errors are classified heuristically and retries are bounded, so the functions 9 | // in this package do not completely eliminate spurious errors. However, they do 10 | // significantly reduce the rate of failure in practice. 11 | // 12 | // If so, the error will likely wrap one of: 13 | // The functions in this package do not completely eliminate spurious errors, 14 | // but substantially reduce their rate of occurrence in practice. 15 | package robustio 16 | 17 | import "time" 18 | 19 | // Rename is like os.Rename, but on Windows retries errors that may occur if the 20 | // file is concurrently read or overwritten. 21 | // 22 | // (See golang.org/issue/31247 and golang.org/issue/32188.) 23 | func Rename(oldpath, newpath string) error { 24 | return rename(oldpath, newpath) 25 | } 26 | 27 | // ReadFile is like os.ReadFile, but on Windows retries errors that may 28 | // occur if the file is concurrently replaced. 29 | // 30 | // (See golang.org/issue/31247 and golang.org/issue/32188.) 31 | func ReadFile(filename string) ([]byte, error) { 32 | return readFile(filename) 33 | } 34 | 35 | // RemoveAll is like os.RemoveAll, but on Windows retries errors that may occur 36 | // if an executable file in the directory has recently been executed. 37 | // 38 | // (See golang.org/issue/19491.) 39 | func RemoveAll(path string) error { 40 | return removeAll(path) 41 | } 42 | 43 | // IsEphemeralError reports whether err is one of the errors that the functions 44 | // in this package attempt to mitigate. 45 | // 46 | // Errors considered ephemeral include: 47 | // - syscall.ERROR_ACCESS_DENIED 48 | // - syscall.ERROR_FILE_NOT_FOUND 49 | // - internal/syscall/windows.ERROR_SHARING_VIOLATION 50 | // 51 | // This set may be expanded in the future; programs must not rely on the 52 | // non-ephemerality of any given error. 53 | func IsEphemeralError(err error) bool { 54 | return isEphemeralError(err) 55 | } 56 | 57 | // A FileID uniquely identifies a file in the file system. 58 | // 59 | // If GetFileID(name1) returns the same ID as GetFileID(name2), the two file 60 | // names denote the same file. 61 | // A FileID is comparable, and thus suitable for use as a map key. 62 | type FileID struct { 63 | device, inode uint64 64 | } 65 | 66 | // GetFileID returns the file system's identifier for the file, and its 67 | // modification time. 68 | // Like os.Stat, it reads through symbolic links. 69 | func GetFileID(filename string) (FileID, time.Time, error) { return getFileID(filename) } 70 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio_darwin.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package robustio 6 | 7 | import ( 8 | "errors" 9 | "syscall" 10 | ) 11 | 12 | const errFileNotFound = syscall.ENOENT 13 | 14 | // isEphemeralError returns true if err may be resolved by waiting. 15 | func isEphemeralError(err error) bool { 16 | var errno syscall.Errno 17 | if errors.As(err, &errno) { 18 | return errno == errFileNotFound 19 | } 20 | return false 21 | } 22 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio_flaky.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build windows || darwin 6 | // +build windows darwin 7 | 8 | package robustio 9 | 10 | import ( 11 | "errors" 12 | "math/rand" 13 | "os" 14 | "syscall" 15 | "time" 16 | ) 17 | 18 | const arbitraryTimeout = 2000 * time.Millisecond 19 | 20 | // retry retries ephemeral errors from f up to an arbitrary timeout 21 | // to work around filesystem flakiness on Windows and Darwin. 22 | func retry(f func() (err error, mayRetry bool)) error { 23 | var ( 24 | bestErr error 25 | lowestErrno syscall.Errno 26 | start time.Time 27 | nextSleep time.Duration = 1 * time.Millisecond 28 | ) 29 | for { 30 | err, mayRetry := f() 31 | if err == nil || !mayRetry { 32 | return err 33 | } 34 | 35 | var errno syscall.Errno 36 | if errors.As(err, &errno) && (lowestErrno == 0 || errno < lowestErrno) { 37 | bestErr = err 38 | lowestErrno = errno 39 | } else if bestErr == nil { 40 | bestErr = err 41 | } 42 | 43 | if start.IsZero() { 44 | start = time.Now() 45 | } else if d := time.Since(start) + nextSleep; d >= arbitraryTimeout { 46 | break 47 | } 48 | time.Sleep(nextSleep) 49 | nextSleep += time.Duration(rand.Int63n(int64(nextSleep))) 50 | } 51 | 52 | return bestErr 53 | } 54 | 55 | // rename is like os.Rename, but retries ephemeral errors. 56 | // 57 | // On Windows it wraps os.Rename, which (as of 2019-06-04) uses MoveFileEx with 58 | // MOVEFILE_REPLACE_EXISTING. 59 | // 60 | // Windows also provides a different system call, ReplaceFile, 61 | // that provides similar semantics, but perhaps preserves more metadata. (The 62 | // documentation on the differences between the two is very sparse.) 63 | // 64 | // Empirical error rates with MoveFileEx are lower under modest concurrency, so 65 | // for now we're sticking with what the os package already provides. 66 | func rename(oldpath, newpath string) (err error) { 67 | return retry(func() (err error, mayRetry bool) { 68 | err = os.Rename(oldpath, newpath) 69 | return err, isEphemeralError(err) 70 | }) 71 | } 72 | 73 | // readFile is like os.ReadFile, but retries ephemeral errors. 74 | func readFile(filename string) ([]byte, error) { 75 | var b []byte 76 | err := retry(func() (err error, mayRetry bool) { 77 | b, err = os.ReadFile(filename) 78 | 79 | // Unlike in rename, we do not retry errFileNotFound here: it can occur 80 | // as a spurious error, but the file may also genuinely not exist, so the 81 | // increase in robustness is probably not worth the extra latency. 82 | return err, isEphemeralError(err) && !errors.Is(err, errFileNotFound) 83 | }) 84 | return b, err 85 | } 86 | 87 | func removeAll(path string) error { 88 | return retry(func() (err error, mayRetry bool) { 89 | err = os.RemoveAll(path) 90 | return err, isEphemeralError(err) 91 | }) 92 | } 93 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio_other.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build !windows && !darwin 6 | // +build !windows,!darwin 7 | 8 | package robustio 9 | 10 | import ( 11 | "os" 12 | ) 13 | 14 | func rename(oldpath, newpath string) error { 15 | return os.Rename(oldpath, newpath) 16 | } 17 | 18 | func readFile(filename string) ([]byte, error) { 19 | return os.ReadFile(filename) 20 | } 21 | 22 | func removeAll(path string) error { 23 | return os.RemoveAll(path) 24 | } 25 | 26 | func isEphemeralError(err error) bool { 27 | return false 28 | } 29 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio_plan9.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build plan9 6 | // +build plan9 7 | 8 | package robustio 9 | 10 | import ( 11 | "os" 12 | "syscall" 13 | "time" 14 | ) 15 | 16 | func getFileID(filename string) (FileID, time.Time, error) { 17 | fi, err := os.Stat(filename) 18 | if err != nil { 19 | return FileID{}, time.Time{}, err 20 | } 21 | dir := fi.Sys().(*syscall.Dir) 22 | return FileID{ 23 | device: uint64(dir.Type)<<32 | uint64(dir.Dev), 24 | inode: dir.Qid.Path, 25 | }, fi.ModTime(), nil 26 | } 27 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio_posix.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build !windows && !plan9 6 | // +build !windows,!plan9 7 | 8 | package robustio 9 | 10 | import ( 11 | "os" 12 | "syscall" 13 | "time" 14 | ) 15 | 16 | func getFileID(filename string) (FileID, time.Time, error) { 17 | fi, err := os.Stat(filename) 18 | if err != nil { 19 | return FileID{}, time.Time{}, err 20 | } 21 | stat := fi.Sys().(*syscall.Stat_t) 22 | return FileID{ 23 | device: uint64(stat.Dev), // (int32 on darwin, uint64 on linux) 24 | inode: stat.Ino, 25 | }, fi.ModTime(), nil 26 | } 27 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/robustio/robustio_windows.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package robustio 6 | 7 | import ( 8 | "errors" 9 | "syscall" 10 | "time" 11 | ) 12 | 13 | const errFileNotFound = syscall.ERROR_FILE_NOT_FOUND 14 | 15 | // isEphemeralError returns true if err may be resolved by waiting. 16 | func isEphemeralError(err error) bool { 17 | var errno syscall.Errno 18 | if errors.As(err, &errno) { 19 | switch errno { 20 | case syscall.ERROR_ACCESS_DENIED, 21 | syscall.ERROR_FILE_NOT_FOUND, 22 | ERROR_SHARING_VIOLATION: 23 | return true 24 | } 25 | } 26 | return false 27 | } 28 | 29 | // Note: it may be convenient to have this helper return fs.FileInfo, but 30 | // implementing this is actually quite involved on Windows. Since we only 31 | // currently use mtime, keep it simple. 32 | func getFileID(filename string) (FileID, time.Time, error) { 33 | filename16, err := syscall.UTF16PtrFromString(filename) 34 | if err != nil { 35 | return FileID{}, time.Time{}, err 36 | } 37 | h, err := syscall.CreateFile(filename16, 0, 0, nil, syscall.OPEN_EXISTING, uint32(syscall.FILE_FLAG_BACKUP_SEMANTICS), 0) 38 | if err != nil { 39 | return FileID{}, time.Time{}, err 40 | } 41 | defer syscall.CloseHandle(h) 42 | var i syscall.ByHandleFileInformation 43 | if err := syscall.GetFileInformationByHandle(h, &i); err != nil { 44 | return FileID{}, time.Time{}, err 45 | } 46 | mtime := time.Unix(0, i.LastWriteTime.Nanoseconds()) 47 | return FileID{ 48 | device: uint64(i.VolumeSerialNumber), 49 | inode: uint64(i.FileIndexHigh)<<32 | uint64(i.FileIndexLow), 50 | }, mtime, nil 51 | } 52 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/stdlib/stdlib.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:generate go run generate.go 6 | 7 | // Package stdlib provides a table of all exported symbols in the 8 | // standard library, along with the version at which they first 9 | // appeared. 10 | package stdlib 11 | 12 | import ( 13 | "fmt" 14 | "strings" 15 | ) 16 | 17 | type Symbol struct { 18 | Name string 19 | Kind Kind 20 | Version Version // Go version that first included the symbol 21 | } 22 | 23 | // A Kind indicates the kind of a symbol: 24 | // function, variable, constant, type, and so on. 25 | type Kind int8 26 | 27 | const ( 28 | Invalid Kind = iota // Example name: 29 | Type // "Buffer" 30 | Func // "Println" 31 | Var // "EOF" 32 | Const // "Pi" 33 | Field // "Point.X" 34 | Method // "(*Buffer).Grow" 35 | ) 36 | 37 | func (kind Kind) String() string { 38 | return [...]string{ 39 | Invalid: "invalid", 40 | Type: "type", 41 | Func: "func", 42 | Var: "var", 43 | Const: "const", 44 | Field: "field", 45 | Method: "method", 46 | }[kind] 47 | } 48 | 49 | // A Version represents a version of Go of the form "go1.%d". 50 | type Version int8 51 | 52 | // String returns a version string of the form "go1.23", without allocating. 53 | func (v Version) String() string { return versions[v] } 54 | 55 | var versions [30]string // (increase constant as needed) 56 | 57 | func init() { 58 | for i := range versions { 59 | versions[i] = fmt.Sprintf("go1.%d", i) 60 | } 61 | } 62 | 63 | // HasPackage reports whether the specified package path is part of 64 | // the standard library's public API. 65 | func HasPackage(path string) bool { 66 | _, ok := PackageSymbols[path] 67 | return ok 68 | } 69 | 70 | // SplitField splits the field symbol name into type and field 71 | // components. It must be called only on Field symbols. 72 | // 73 | // Example: "File.Package" -> ("File", "Package") 74 | func (sym *Symbol) SplitField() (typename, name string) { 75 | if sym.Kind != Field { 76 | panic("not a field") 77 | } 78 | typename, name, _ = strings.Cut(sym.Name, ".") 79 | return 80 | } 81 | 82 | // SplitMethod splits the method symbol name into pointer, receiver, 83 | // and method components. It must be called only on Method symbols. 84 | // 85 | // Example: "(*Buffer).Grow" -> (true, "Buffer", "Grow") 86 | func (sym *Symbol) SplitMethod() (ptr bool, recv, name string) { 87 | if sym.Kind != Method { 88 | panic("not a method") 89 | } 90 | recv, name, _ = strings.Cut(sym.Name, ".") 91 | recv = recv[len("(") : len(recv)-len(")")] 92 | ptr = recv[0] == '*' 93 | if ptr { 94 | recv = recv[len("*"):] 95 | } 96 | return 97 | } 98 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/testenv/testenv_notunix.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build !(unix || aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris) 6 | // +build !unix,!aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris 7 | 8 | package testenv 9 | 10 | import "os" 11 | 12 | // Sigquit is the signal to send to kill a hanging subprocess. 13 | // On Unix we send SIGQUIT, but on non-Unix we only have os.Kill. 14 | var Sigquit = os.Kill 15 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/testenv/testenv_unix.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build unix || aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris 6 | // +build unix aix darwin dragonfly freebsd linux netbsd openbsd solaris 7 | 8 | package testenv 9 | 10 | import "syscall" 11 | 12 | // Sigquit is the signal to send to kill a hanging subprocess. 13 | // Send SIGQUIT to get a stack trace. 14 | var Sigquit = syscall.SIGQUIT 15 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typeparams/common.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package typeparams contains common utilities for writing tools that 6 | // interact with generic Go code, as introduced with Go 1.18. It 7 | // supplements the standard library APIs. Notably, the StructuralTerms 8 | // API computes a minimal representation of the structural 9 | // restrictions on a type parameter. 10 | // 11 | // An external version of these APIs is available in the 12 | // golang.org/x/exp/typeparams module. 13 | package typeparams 14 | 15 | import ( 16 | "go/ast" 17 | "go/token" 18 | "go/types" 19 | ) 20 | 21 | // UnpackIndexExpr extracts data from AST nodes that represent index 22 | // expressions. 23 | // 24 | // For an ast.IndexExpr, the resulting indices slice will contain exactly one 25 | // index expression. For an ast.IndexListExpr (go1.18+), it may have a variable 26 | // number of index expressions. 27 | // 28 | // For nodes that don't represent index expressions, the first return value of 29 | // UnpackIndexExpr will be nil. 30 | func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) { 31 | switch e := n.(type) { 32 | case *ast.IndexExpr: 33 | return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack 34 | case *ast.IndexListExpr: 35 | return e.X, e.Lbrack, e.Indices, e.Rbrack 36 | } 37 | return nil, token.NoPos, nil, token.NoPos 38 | } 39 | 40 | // PackIndexExpr returns an *ast.IndexExpr or *ast.IndexListExpr, depending on 41 | // the cardinality of indices. Calling PackIndexExpr with len(indices) == 0 42 | // will panic. 43 | func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) ast.Expr { 44 | switch len(indices) { 45 | case 0: 46 | panic("empty indices") 47 | case 1: 48 | return &ast.IndexExpr{ 49 | X: x, 50 | Lbrack: lbrack, 51 | Index: indices[0], 52 | Rbrack: rbrack, 53 | } 54 | default: 55 | return &ast.IndexListExpr{ 56 | X: x, 57 | Lbrack: lbrack, 58 | Indices: indices, 59 | Rbrack: rbrack, 60 | } 61 | } 62 | } 63 | 64 | // IsTypeParam reports whether t is a type parameter (or an alias of one). 65 | func IsTypeParam(t types.Type) bool { 66 | _, ok := types.Unalias(t).(*types.TypeParam) 67 | return ok 68 | } 69 | 70 | // GenericAssignableTo is a generalization of types.AssignableTo that 71 | // implements the following rule for uninstantiated generic types: 72 | // 73 | // If V and T are generic named types, then V is considered assignable to T if, 74 | // for every possible instantiation of V[A_1, ..., A_N], the instantiation 75 | // T[A_1, ..., A_N] is valid and V[A_1, ..., A_N] implements T[A_1, ..., A_N]. 76 | // 77 | // If T has structural constraints, they must be satisfied by V. 78 | // 79 | // For example, consider the following type declarations: 80 | // 81 | // type Interface[T any] interface { 82 | // Accept(T) 83 | // } 84 | // 85 | // type Container[T any] struct { 86 | // Element T 87 | // } 88 | // 89 | // func (c Container[T]) Accept(t T) { c.Element = t } 90 | // 91 | // In this case, GenericAssignableTo reports that instantiations of Container 92 | // are assignable to the corresponding instantiation of Interface. 93 | func GenericAssignableTo(ctxt *types.Context, V, T types.Type) bool { 94 | V = types.Unalias(V) 95 | T = types.Unalias(T) 96 | 97 | // If V and T are not both named, or do not have matching non-empty type 98 | // parameter lists, fall back on types.AssignableTo. 99 | 100 | VN, Vnamed := V.(*types.Named) 101 | TN, Tnamed := T.(*types.Named) 102 | if !Vnamed || !Tnamed { 103 | return types.AssignableTo(V, T) 104 | } 105 | 106 | vtparams := VN.TypeParams() 107 | ttparams := TN.TypeParams() 108 | if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || VN.TypeArgs().Len() != 0 || TN.TypeArgs().Len() != 0 { 109 | return types.AssignableTo(V, T) 110 | } 111 | 112 | // V and T have the same (non-zero) number of type params. Instantiate both 113 | // with the type parameters of V. This must always succeed for V, and will 114 | // succeed for T if and only if the type set of each type parameter of V is a 115 | // subset of the type set of the corresponding type parameter of T, meaning 116 | // that every instantiation of V corresponds to a valid instantiation of T. 117 | 118 | // Minor optimization: ensure we share a context across the two 119 | // instantiations below. 120 | if ctxt == nil { 121 | ctxt = types.NewContext() 122 | } 123 | 124 | var targs []types.Type 125 | for i := 0; i < vtparams.Len(); i++ { 126 | targs = append(targs, vtparams.At(i)) 127 | } 128 | 129 | vinst, err := types.Instantiate(ctxt, V, targs, true) 130 | if err != nil { 131 | panic("type parameters should satisfy their own constraints") 132 | } 133 | 134 | tinst, err := types.Instantiate(ctxt, T, targs, true) 135 | if err != nil { 136 | return false 137 | } 138 | 139 | return types.AssignableTo(vinst, tinst) 140 | } 141 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typeparams/coretype.go: -------------------------------------------------------------------------------- 1 | // Copyright 2022 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typeparams 6 | 7 | import ( 8 | "fmt" 9 | "go/types" 10 | ) 11 | 12 | // CoreType returns the core type of T or nil if T does not have a core type. 13 | // 14 | // See https://go.dev/ref/spec#Core_types for the definition of a core type. 15 | func CoreType(T types.Type) types.Type { 16 | U := T.Underlying() 17 | if _, ok := U.(*types.Interface); !ok { 18 | return U // for non-interface types, 19 | } 20 | 21 | terms, err := NormalTerms(U) 22 | if len(terms) == 0 || err != nil { 23 | // len(terms) -> empty type set of interface. 24 | // err != nil => U is invalid, exceeds complexity bounds, or has an empty type set. 25 | return nil // no core type. 26 | } 27 | 28 | U = terms[0].Type().Underlying() 29 | var identical int // i in [0,identical) => Identical(U, terms[i].Type().Underlying()) 30 | for identical = 1; identical < len(terms); identical++ { 31 | if !types.Identical(U, terms[identical].Type().Underlying()) { 32 | break 33 | } 34 | } 35 | 36 | if identical == len(terms) { 37 | // https://go.dev/ref/spec#Core_types 38 | // "There is a single type U which is the underlying type of all types in the type set of T" 39 | return U 40 | } 41 | ch, ok := U.(*types.Chan) 42 | if !ok { 43 | return nil // no core type as identical < len(terms) and U is not a channel. 44 | } 45 | // https://go.dev/ref/spec#Core_types 46 | // "the type chan E if T contains only bidirectional channels, or the type chan<- E or 47 | // <-chan E depending on the direction of the directional channels present." 48 | for chans := identical; chans < len(terms); chans++ { 49 | curr, ok := terms[chans].Type().Underlying().(*types.Chan) 50 | if !ok { 51 | return nil 52 | } 53 | if !types.Identical(ch.Elem(), curr.Elem()) { 54 | return nil // channel elements are not identical. 55 | } 56 | if ch.Dir() == types.SendRecv { 57 | // ch is bidirectional. We can safely always use curr's direction. 58 | ch = curr 59 | } else if curr.Dir() != types.SendRecv && ch.Dir() != curr.Dir() { 60 | // ch and curr are not bidirectional and not the same direction. 61 | return nil 62 | } 63 | } 64 | return ch 65 | } 66 | 67 | // NormalTerms returns a slice of terms representing the normalized structural 68 | // type restrictions of a type, if any. 69 | // 70 | // For all types other than *types.TypeParam, *types.Interface, and 71 | // *types.Union, this is just a single term with Tilde() == false and 72 | // Type() == typ. For *types.TypeParam, *types.Interface, and *types.Union, see 73 | // below. 74 | // 75 | // Structural type restrictions of a type parameter are created via 76 | // non-interface types embedded in its constraint interface (directly, or via a 77 | // chain of interface embeddings). For example, in the declaration type 78 | // T[P interface{~int; m()}] int the structural restriction of the type 79 | // parameter P is ~int. 80 | // 81 | // With interface embedding and unions, the specification of structural type 82 | // restrictions may be arbitrarily complex. For example, consider the 83 | // following: 84 | // 85 | // type A interface{ ~string|~[]byte } 86 | // 87 | // type B interface{ int|string } 88 | // 89 | // type C interface { ~string|~int } 90 | // 91 | // type T[P interface{ A|B; C }] int 92 | // 93 | // In this example, the structural type restriction of P is ~string|int: A|B 94 | // expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int, 95 | // which when intersected with C (~string|~int) yields ~string|int. 96 | // 97 | // NormalTerms computes these expansions and reductions, producing a 98 | // "normalized" form of the embeddings. A structural restriction is normalized 99 | // if it is a single union containing no interface terms, and is minimal in the 100 | // sense that removing any term changes the set of types satisfying the 101 | // constraint. It is left as a proof for the reader that, modulo sorting, there 102 | // is exactly one such normalized form. 103 | // 104 | // Because the minimal representation always takes this form, NormalTerms 105 | // returns a slice of tilde terms corresponding to the terms of the union in 106 | // the normalized structural restriction. An error is returned if the type is 107 | // invalid, exceeds complexity bounds, or has an empty type set. In the latter 108 | // case, NormalTerms returns ErrEmptyTypeSet. 109 | // 110 | // NormalTerms makes no guarantees about the order of terms, except that it 111 | // is deterministic. 112 | func NormalTerms(typ types.Type) ([]*types.Term, error) { 113 | switch typ := typ.Underlying().(type) { 114 | case *types.TypeParam: 115 | return StructuralTerms(typ) 116 | case *types.Union: 117 | return UnionTermSet(typ) 118 | case *types.Interface: 119 | return InterfaceTermSet(typ) 120 | default: 121 | return []*types.Term{types.NewTerm(false, typ)}, nil 122 | } 123 | } 124 | 125 | // Deref returns the type of the variable pointed to by t, 126 | // if t's core type is a pointer; otherwise it returns t. 127 | // 128 | // Do not assume that Deref(T)==T implies T is not a pointer: 129 | // consider "type T *T", for example. 130 | // 131 | // TODO(adonovan): ideally this would live in typesinternal, but that 132 | // creates an import cycle. Move there when we melt this package down. 133 | func Deref(t types.Type) types.Type { 134 | if ptr, ok := CoreType(t).(*types.Pointer); ok { 135 | return ptr.Elem() 136 | } 137 | return t 138 | } 139 | 140 | // MustDeref returns the type of the variable pointed to by t. 141 | // It panics if t's core type is not a pointer. 142 | // 143 | // TODO(adonovan): ideally this would live in typesinternal, but that 144 | // creates an import cycle. Move there when we melt this package down. 145 | func MustDeref(t types.Type) types.Type { 146 | if ptr, ok := CoreType(t).(*types.Pointer); ok { 147 | return ptr.Elem() 148 | } 149 | panic(fmt.Sprintf("%v is not a pointer", t)) 150 | } 151 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typeparams/free.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typeparams 6 | 7 | import ( 8 | "go/types" 9 | 10 | "golang.org/x/tools/internal/aliases" 11 | ) 12 | 13 | // Free is a memoization of the set of free type parameters within a 14 | // type. It makes a sequence of calls to [Free.Has] for overlapping 15 | // types more efficient. The zero value is ready for use. 16 | // 17 | // NOTE: Adapted from go/types/infer.go. If it is later exported, factor. 18 | type Free struct { 19 | seen map[types.Type]bool 20 | } 21 | 22 | // Has reports whether the specified type has a free type parameter. 23 | func (w *Free) Has(typ types.Type) (res bool) { 24 | // detect cycles 25 | if x, ok := w.seen[typ]; ok { 26 | return x 27 | } 28 | if w.seen == nil { 29 | w.seen = make(map[types.Type]bool) 30 | } 31 | w.seen[typ] = false 32 | defer func() { 33 | w.seen[typ] = res 34 | }() 35 | 36 | switch t := typ.(type) { 37 | case nil, *types.Basic: // TODO(gri) should nil be handled here? 38 | break 39 | 40 | case *types.Alias: 41 | if aliases.TypeParams(t).Len() > aliases.TypeArgs(t).Len() { 42 | return true // This is an uninstantiated Alias. 43 | } 44 | // The expansion of an alias can have free type parameters, 45 | // whether or not the alias itself has type parameters: 46 | // 47 | // func _[K comparable]() { 48 | // type Set = map[K]bool // free(Set) = {K} 49 | // type MapTo[V] = map[K]V // free(Map[foo]) = {V} 50 | // } 51 | // 52 | // So, we must Unalias. 53 | return w.Has(types.Unalias(t)) 54 | 55 | case *types.Array: 56 | return w.Has(t.Elem()) 57 | 58 | case *types.Slice: 59 | return w.Has(t.Elem()) 60 | 61 | case *types.Struct: 62 | for i, n := 0, t.NumFields(); i < n; i++ { 63 | if w.Has(t.Field(i).Type()) { 64 | return true 65 | } 66 | } 67 | 68 | case *types.Pointer: 69 | return w.Has(t.Elem()) 70 | 71 | case *types.Tuple: 72 | n := t.Len() 73 | for i := 0; i < n; i++ { 74 | if w.Has(t.At(i).Type()) { 75 | return true 76 | } 77 | } 78 | 79 | case *types.Signature: 80 | // t.tparams may not be nil if we are looking at a signature 81 | // of a generic function type (or an interface method) that is 82 | // part of the type we're testing. We don't care about these type 83 | // parameters. 84 | // Similarly, the receiver of a method may declare (rather than 85 | // use) type parameters, we don't care about those either. 86 | // Thus, we only need to look at the input and result parameters. 87 | return w.Has(t.Params()) || w.Has(t.Results()) 88 | 89 | case *types.Interface: 90 | for i, n := 0, t.NumMethods(); i < n; i++ { 91 | if w.Has(t.Method(i).Type()) { 92 | return true 93 | } 94 | } 95 | terms, err := InterfaceTermSet(t) 96 | if err != nil { 97 | return false // ill typed 98 | } 99 | for _, term := range terms { 100 | if w.Has(term.Type()) { 101 | return true 102 | } 103 | } 104 | 105 | case *types.Map: 106 | return w.Has(t.Key()) || w.Has(t.Elem()) 107 | 108 | case *types.Chan: 109 | return w.Has(t.Elem()) 110 | 111 | case *types.Named: 112 | args := t.TypeArgs() 113 | if params := t.TypeParams(); params.Len() > args.Len() { 114 | return true // this is an uninstantiated named type. 115 | } 116 | for i, n := 0, args.Len(); i < n; i++ { 117 | if w.Has(args.At(i)) { 118 | return true 119 | } 120 | } 121 | return w.Has(t.Underlying()) // recurse for types local to parameterized functions 122 | 123 | case *types.TypeParam: 124 | return true 125 | 126 | default: 127 | panic(t) // unreachable 128 | } 129 | 130 | return false 131 | } 132 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typeparams/termlist.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Code generated by copytermlist.go DO NOT EDIT. 6 | 7 | package typeparams 8 | 9 | import ( 10 | "bytes" 11 | "go/types" 12 | ) 13 | 14 | // A termlist represents the type set represented by the union 15 | // t1 ∪ y2 ∪ ... tn of the type sets of the terms t1 to tn. 16 | // A termlist is in normal form if all terms are disjoint. 17 | // termlist operations don't require the operands to be in 18 | // normal form. 19 | type termlist []*term 20 | 21 | // allTermlist represents the set of all types. 22 | // It is in normal form. 23 | var allTermlist = termlist{new(term)} 24 | 25 | // String prints the termlist exactly (without normalization). 26 | func (xl termlist) String() string { 27 | if len(xl) == 0 { 28 | return "∅" 29 | } 30 | var buf bytes.Buffer 31 | for i, x := range xl { 32 | if i > 0 { 33 | buf.WriteString(" | ") 34 | } 35 | buf.WriteString(x.String()) 36 | } 37 | return buf.String() 38 | } 39 | 40 | // isEmpty reports whether the termlist xl represents the empty set of types. 41 | func (xl termlist) isEmpty() bool { 42 | // If there's a non-nil term, the entire list is not empty. 43 | // If the termlist is in normal form, this requires at most 44 | // one iteration. 45 | for _, x := range xl { 46 | if x != nil { 47 | return false 48 | } 49 | } 50 | return true 51 | } 52 | 53 | // isAll reports whether the termlist xl represents the set of all types. 54 | func (xl termlist) isAll() bool { 55 | // If there's a 𝓤 term, the entire list is 𝓤. 56 | // If the termlist is in normal form, this requires at most 57 | // one iteration. 58 | for _, x := range xl { 59 | if x != nil && x.typ == nil { 60 | return true 61 | } 62 | } 63 | return false 64 | } 65 | 66 | // norm returns the normal form of xl. 67 | func (xl termlist) norm() termlist { 68 | // Quadratic algorithm, but good enough for now. 69 | // TODO(gri) fix asymptotic performance 70 | used := make([]bool, len(xl)) 71 | var rl termlist 72 | for i, xi := range xl { 73 | if xi == nil || used[i] { 74 | continue 75 | } 76 | for j := i + 1; j < len(xl); j++ { 77 | xj := xl[j] 78 | if xj == nil || used[j] { 79 | continue 80 | } 81 | if u1, u2 := xi.union(xj); u2 == nil { 82 | // If we encounter a 𝓤 term, the entire list is 𝓤. 83 | // Exit early. 84 | // (Note that this is not just an optimization; 85 | // if we continue, we may end up with a 𝓤 term 86 | // and other terms and the result would not be 87 | // in normal form.) 88 | if u1.typ == nil { 89 | return allTermlist 90 | } 91 | xi = u1 92 | used[j] = true // xj is now unioned into xi - ignore it in future iterations 93 | } 94 | } 95 | rl = append(rl, xi) 96 | } 97 | return rl 98 | } 99 | 100 | // union returns the union xl ∪ yl. 101 | func (xl termlist) union(yl termlist) termlist { 102 | return append(xl, yl...).norm() 103 | } 104 | 105 | // intersect returns the intersection xl ∩ yl. 106 | func (xl termlist) intersect(yl termlist) termlist { 107 | if xl.isEmpty() || yl.isEmpty() { 108 | return nil 109 | } 110 | 111 | // Quadratic algorithm, but good enough for now. 112 | // TODO(gri) fix asymptotic performance 113 | var rl termlist 114 | for _, x := range xl { 115 | for _, y := range yl { 116 | if r := x.intersect(y); r != nil { 117 | rl = append(rl, r) 118 | } 119 | } 120 | } 121 | return rl.norm() 122 | } 123 | 124 | // equal reports whether xl and yl represent the same type set. 125 | func (xl termlist) equal(yl termlist) bool { 126 | // TODO(gri) this should be more efficient 127 | return xl.subsetOf(yl) && yl.subsetOf(xl) 128 | } 129 | 130 | // includes reports whether t ∈ xl. 131 | func (xl termlist) includes(t types.Type) bool { 132 | for _, x := range xl { 133 | if x.includes(t) { 134 | return true 135 | } 136 | } 137 | return false 138 | } 139 | 140 | // supersetOf reports whether y ⊆ xl. 141 | func (xl termlist) supersetOf(y *term) bool { 142 | for _, x := range xl { 143 | if y.subsetOf(x) { 144 | return true 145 | } 146 | } 147 | return false 148 | } 149 | 150 | // subsetOf reports whether xl ⊆ yl. 151 | func (xl termlist) subsetOf(yl termlist) bool { 152 | if yl.isEmpty() { 153 | return xl.isEmpty() 154 | } 155 | 156 | // each term x of xl must be a subset of yl 157 | for _, x := range xl { 158 | if !yl.supersetOf(x) { 159 | return false // x is not a subset yl 160 | } 161 | } 162 | return true 163 | } 164 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typeparams/typeterm.go: -------------------------------------------------------------------------------- 1 | // Copyright 2021 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Code generated by copytermlist.go DO NOT EDIT. 6 | 7 | package typeparams 8 | 9 | import "go/types" 10 | 11 | // A term describes elementary type sets: 12 | // 13 | // ∅: (*term)(nil) == ∅ // set of no types (empty set) 14 | // 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse) 15 | // T: &term{false, T} == {T} // set of type T 16 | // ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t 17 | type term struct { 18 | tilde bool // valid if typ != nil 19 | typ types.Type 20 | } 21 | 22 | func (x *term) String() string { 23 | switch { 24 | case x == nil: 25 | return "∅" 26 | case x.typ == nil: 27 | return "𝓤" 28 | case x.tilde: 29 | return "~" + x.typ.String() 30 | default: 31 | return x.typ.String() 32 | } 33 | } 34 | 35 | // equal reports whether x and y represent the same type set. 36 | func (x *term) equal(y *term) bool { 37 | // easy cases 38 | switch { 39 | case x == nil || y == nil: 40 | return x == y 41 | case x.typ == nil || y.typ == nil: 42 | return x.typ == y.typ 43 | } 44 | // ∅ ⊂ x, y ⊂ 𝓤 45 | 46 | return x.tilde == y.tilde && types.Identical(x.typ, y.typ) 47 | } 48 | 49 | // union returns the union x ∪ y: zero, one, or two non-nil terms. 50 | func (x *term) union(y *term) (_, _ *term) { 51 | // easy cases 52 | switch { 53 | case x == nil && y == nil: 54 | return nil, nil // ∅ ∪ ∅ == ∅ 55 | case x == nil: 56 | return y, nil // ∅ ∪ y == y 57 | case y == nil: 58 | return x, nil // x ∪ ∅ == x 59 | case x.typ == nil: 60 | return x, nil // 𝓤 ∪ y == 𝓤 61 | case y.typ == nil: 62 | return y, nil // x ∪ 𝓤 == 𝓤 63 | } 64 | // ∅ ⊂ x, y ⊂ 𝓤 65 | 66 | if x.disjoint(y) { 67 | return x, y // x ∪ y == (x, y) if x ∩ y == ∅ 68 | } 69 | // x.typ == y.typ 70 | 71 | // ~t ∪ ~t == ~t 72 | // ~t ∪ T == ~t 73 | // T ∪ ~t == ~t 74 | // T ∪ T == T 75 | if x.tilde || !y.tilde { 76 | return x, nil 77 | } 78 | return y, nil 79 | } 80 | 81 | // intersect returns the intersection x ∩ y. 82 | func (x *term) intersect(y *term) *term { 83 | // easy cases 84 | switch { 85 | case x == nil || y == nil: 86 | return nil // ∅ ∩ y == ∅ and ∩ ∅ == ∅ 87 | case x.typ == nil: 88 | return y // 𝓤 ∩ y == y 89 | case y.typ == nil: 90 | return x // x ∩ 𝓤 == x 91 | } 92 | // ∅ ⊂ x, y ⊂ 𝓤 93 | 94 | if x.disjoint(y) { 95 | return nil // x ∩ y == ∅ if x ∩ y == ∅ 96 | } 97 | // x.typ == y.typ 98 | 99 | // ~t ∩ ~t == ~t 100 | // ~t ∩ T == T 101 | // T ∩ ~t == T 102 | // T ∩ T == T 103 | if !x.tilde || y.tilde { 104 | return x 105 | } 106 | return y 107 | } 108 | 109 | // includes reports whether t ∈ x. 110 | func (x *term) includes(t types.Type) bool { 111 | // easy cases 112 | switch { 113 | case x == nil: 114 | return false // t ∈ ∅ == false 115 | case x.typ == nil: 116 | return true // t ∈ 𝓤 == true 117 | } 118 | // ∅ ⊂ x ⊂ 𝓤 119 | 120 | u := t 121 | if x.tilde { 122 | u = under(u) 123 | } 124 | return types.Identical(x.typ, u) 125 | } 126 | 127 | // subsetOf reports whether x ⊆ y. 128 | func (x *term) subsetOf(y *term) bool { 129 | // easy cases 130 | switch { 131 | case x == nil: 132 | return true // ∅ ⊆ y == true 133 | case y == nil: 134 | return false // x ⊆ ∅ == false since x != ∅ 135 | case y.typ == nil: 136 | return true // x ⊆ 𝓤 == true 137 | case x.typ == nil: 138 | return false // 𝓤 ⊆ y == false since y != 𝓤 139 | } 140 | // ∅ ⊂ x, y ⊂ 𝓤 141 | 142 | if x.disjoint(y) { 143 | return false // x ⊆ y == false if x ∩ y == ∅ 144 | } 145 | // x.typ == y.typ 146 | 147 | // ~t ⊆ ~t == true 148 | // ~t ⊆ T == false 149 | // T ⊆ ~t == true 150 | // T ⊆ T == true 151 | return !x.tilde || y.tilde 152 | } 153 | 154 | // disjoint reports whether x ∩ y == ∅. 155 | // x.typ and y.typ must not be nil. 156 | func (x *term) disjoint(y *term) bool { 157 | if debug && (x.typ == nil || y.typ == nil) { 158 | panic("invalid argument(s)") 159 | } 160 | ux := x.typ 161 | if y.tilde { 162 | ux = under(ux) 163 | } 164 | uy := y.typ 165 | if x.tilde { 166 | uy = under(uy) 167 | } 168 | return !types.Identical(ux, uy) 169 | } 170 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typesinternal/element.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typesinternal 6 | 7 | import ( 8 | "fmt" 9 | "go/types" 10 | 11 | "golang.org/x/tools/go/types/typeutil" 12 | ) 13 | 14 | // ForEachElement calls f for type T and each type reachable from its 15 | // type through reflection. It does this by recursively stripping off 16 | // type constructors; in addition, for each named type N, the type *N 17 | // is added to the result as it may have additional methods. 18 | // 19 | // The caller must provide an initially empty set used to de-duplicate 20 | // identical types, potentially across multiple calls to ForEachElement. 21 | // (Its final value holds all the elements seen, matching the arguments 22 | // passed to f.) 23 | // 24 | // TODO(adonovan): share/harmonize with go/callgraph/rta. 25 | func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T types.Type, f func(types.Type)) { 26 | var visit func(T types.Type, skip bool) 27 | visit = func(T types.Type, skip bool) { 28 | if !skip { 29 | if seen, _ := rtypes.Set(T, true).(bool); seen { 30 | return // de-dup 31 | } 32 | 33 | f(T) // notify caller of new element type 34 | } 35 | 36 | // Recursion over signatures of each method. 37 | tmset := msets.MethodSet(T) 38 | for i := 0; i < tmset.Len(); i++ { 39 | sig := tmset.At(i).Type().(*types.Signature) 40 | // It is tempting to call visit(sig, false) 41 | // but, as noted in golang.org/cl/65450043, 42 | // the Signature.Recv field is ignored by 43 | // types.Identical and typeutil.Map, which 44 | // is confusing at best. 45 | // 46 | // More importantly, the true signature rtype 47 | // reachable from a method using reflection 48 | // has no receiver but an extra ordinary parameter. 49 | // For the Read method of io.Reader we want: 50 | // func(Reader, []byte) (int, error) 51 | // but here sig is: 52 | // func([]byte) (int, error) 53 | // with .Recv = Reader (though it is hard to 54 | // notice because it doesn't affect Signature.String 55 | // or types.Identical). 56 | // 57 | // TODO(adonovan): construct and visit the correct 58 | // non-method signature with an extra parameter 59 | // (though since unnamed func types have no methods 60 | // there is essentially no actual demand for this). 61 | // 62 | // TODO(adonovan): document whether or not it is 63 | // safe to skip non-exported methods (as RTA does). 64 | visit(sig.Params(), true) // skip the Tuple 65 | visit(sig.Results(), true) // skip the Tuple 66 | } 67 | 68 | switch T := T.(type) { 69 | case *types.Alias: 70 | visit(types.Unalias(T), skip) // emulates the pre-Alias behavior 71 | 72 | case *types.Basic: 73 | // nop 74 | 75 | case *types.Interface: 76 | // nop---handled by recursion over method set. 77 | 78 | case *types.Pointer: 79 | visit(T.Elem(), false) 80 | 81 | case *types.Slice: 82 | visit(T.Elem(), false) 83 | 84 | case *types.Chan: 85 | visit(T.Elem(), false) 86 | 87 | case *types.Map: 88 | visit(T.Key(), false) 89 | visit(T.Elem(), false) 90 | 91 | case *types.Signature: 92 | if T.Recv() != nil { 93 | panic(fmt.Sprintf("Signature %s has Recv %s", T, T.Recv())) 94 | } 95 | visit(T.Params(), true) // skip the Tuple 96 | visit(T.Results(), true) // skip the Tuple 97 | 98 | case *types.Named: 99 | // A pointer-to-named type can be derived from a named 100 | // type via reflection. It may have methods too. 101 | visit(types.NewPointer(T), false) 102 | 103 | // Consider 'type T struct{S}' where S has methods. 104 | // Reflection provides no way to get from T to struct{S}, 105 | // only to S, so the method set of struct{S} is unwanted, 106 | // so set 'skip' flag during recursion. 107 | visit(T.Underlying(), true) // skip the unnamed type 108 | 109 | case *types.Array: 110 | visit(T.Elem(), false) 111 | 112 | case *types.Struct: 113 | for i, n := 0, T.NumFields(); i < n; i++ { 114 | // TODO(adonovan): document whether or not 115 | // it is safe to skip non-exported fields. 116 | visit(T.Field(i).Type(), false) 117 | } 118 | 119 | case *types.Tuple: 120 | for i, n := 0, T.Len(); i < n; i++ { 121 | visit(T.At(i).Type(), false) 122 | } 123 | 124 | case *types.TypeParam, *types.Union: 125 | // forEachReachable must not be called on parameterized types. 126 | panic(T) 127 | 128 | default: 129 | panic(T) 130 | } 131 | } 132 | visit(T, false) 133 | } 134 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typesinternal/recv.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typesinternal 6 | 7 | import ( 8 | "go/types" 9 | ) 10 | 11 | // ReceiverNamed returns the named type (if any) associated with the 12 | // type of recv, which may be of the form N or *N, or aliases thereof. 13 | // It also reports whether a Pointer was present. 14 | func ReceiverNamed(recv *types.Var) (isPtr bool, named *types.Named) { 15 | t := recv.Type() 16 | if ptr, ok := types.Unalias(t).(*types.Pointer); ok { 17 | isPtr = true 18 | t = ptr.Elem() 19 | } 20 | named, _ = types.Unalias(t).(*types.Named) 21 | return 22 | } 23 | 24 | // Unpointer returns T given *T or an alias thereof. 25 | // For all other types it is the identity function. 26 | // It does not look at underlying types. 27 | // The result may be an alias. 28 | // 29 | // Use this function to strip off the optional pointer on a receiver 30 | // in a field or method selection, without losing the named type 31 | // (which is needed to compute the method set). 32 | // 33 | // See also [typeparams.MustDeref], which removes one level of 34 | // indirection from the type, regardless of named types (analogous to 35 | // a LOAD instruction). 36 | func Unpointer(t types.Type) types.Type { 37 | if ptr, ok := types.Unalias(t).(*types.Pointer); ok { 38 | return ptr.Elem() 39 | } 40 | return t 41 | } 42 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typesinternal/toonew.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package typesinternal 6 | 7 | import ( 8 | "go/types" 9 | 10 | "golang.org/x/tools/internal/stdlib" 11 | "golang.org/x/tools/internal/versions" 12 | ) 13 | 14 | // TooNewStdSymbols computes the set of package-level symbols 15 | // exported by pkg that are not available at the specified version. 16 | // The result maps each symbol to its minimum version. 17 | // 18 | // The pkg is allowed to contain type errors. 19 | func TooNewStdSymbols(pkg *types.Package, version string) map[types.Object]string { 20 | disallowed := make(map[types.Object]string) 21 | 22 | // Pass 1: package-level symbols. 23 | symbols := stdlib.PackageSymbols[pkg.Path()] 24 | for _, sym := range symbols { 25 | symver := sym.Version.String() 26 | if versions.Before(version, symver) { 27 | switch sym.Kind { 28 | case stdlib.Func, stdlib.Var, stdlib.Const, stdlib.Type: 29 | disallowed[pkg.Scope().Lookup(sym.Name)] = symver 30 | } 31 | } 32 | } 33 | 34 | // Pass 2: fields and methods. 35 | // 36 | // We allow fields and methods if their associated type is 37 | // disallowed, as otherwise we would report false positives 38 | // for compatibility shims. Consider: 39 | // 40 | // //go:build go1.22 41 | // type T struct { F std.Real } // correct new API 42 | // 43 | // //go:build !go1.22 44 | // type T struct { F fake } // shim 45 | // type fake struct { ... } 46 | // func (fake) M () {} 47 | // 48 | // These alternative declarations of T use either the std.Real 49 | // type, introduced in go1.22, or a fake type, for the field 50 | // F. (The fakery could be arbitrarily deep, involving more 51 | // nested fields and methods than are shown here.) Clients 52 | // that use the compatibility shim T will compile with any 53 | // version of go, whether older or newer than go1.22, but only 54 | // the newer version will use the std.Real implementation. 55 | // 56 | // Now consider a reference to method M in new(T).F.M() in a 57 | // module that requires a minimum of go1.21. The analysis may 58 | // occur using a version of Go higher than 1.21, selecting the 59 | // first version of T, so the method M is Real.M. This would 60 | // spuriously cause the analyzer to report a reference to a 61 | // too-new symbol even though this expression compiles just 62 | // fine (with the fake implementation) using go1.21. 63 | for _, sym := range symbols { 64 | symVersion := sym.Version.String() 65 | if !versions.Before(version, symVersion) { 66 | continue // allowed 67 | } 68 | 69 | var obj types.Object 70 | switch sym.Kind { 71 | case stdlib.Field: 72 | typename, name := sym.SplitField() 73 | if t := pkg.Scope().Lookup(typename); t != nil && disallowed[t] == "" { 74 | obj, _, _ = types.LookupFieldOrMethod(t.Type(), false, pkg, name) 75 | } 76 | 77 | case stdlib.Method: 78 | ptr, recvname, name := sym.SplitMethod() 79 | if t := pkg.Scope().Lookup(recvname); t != nil && disallowed[t] == "" { 80 | obj, _, _ = types.LookupFieldOrMethod(t.Type(), ptr, pkg, name) 81 | } 82 | } 83 | if obj != nil { 84 | disallowed[obj] = symVersion 85 | } 86 | } 87 | 88 | return disallowed 89 | } 90 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/typesinternal/types.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package typesinternal provides access to internal go/types APIs that are not 6 | // yet exported. 7 | package typesinternal 8 | 9 | import ( 10 | "go/token" 11 | "go/types" 12 | "reflect" 13 | "unsafe" 14 | 15 | "golang.org/x/tools/internal/aliases" 16 | ) 17 | 18 | func SetUsesCgo(conf *types.Config) bool { 19 | v := reflect.ValueOf(conf).Elem() 20 | 21 | f := v.FieldByName("go115UsesCgo") 22 | if !f.IsValid() { 23 | f = v.FieldByName("UsesCgo") 24 | if !f.IsValid() { 25 | return false 26 | } 27 | } 28 | 29 | addr := unsafe.Pointer(f.UnsafeAddr()) 30 | *(*bool)(addr) = true 31 | 32 | return true 33 | } 34 | 35 | // ReadGo116ErrorData extracts additional information from types.Error values 36 | // generated by Go version 1.16 and later: the error code, start position, and 37 | // end position. If all positions are valid, start <= err.Pos <= end. 38 | // 39 | // If the data could not be read, the final result parameter will be false. 40 | func ReadGo116ErrorData(err types.Error) (code ErrorCode, start, end token.Pos, ok bool) { 41 | var data [3]int 42 | // By coincidence all of these fields are ints, which simplifies things. 43 | v := reflect.ValueOf(err) 44 | for i, name := range []string{"go116code", "go116start", "go116end"} { 45 | f := v.FieldByName(name) 46 | if !f.IsValid() { 47 | return 0, 0, 0, false 48 | } 49 | data[i] = int(f.Int()) 50 | } 51 | return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true 52 | } 53 | 54 | // NameRelativeTo returns a types.Qualifier that qualifies members of 55 | // all packages other than pkg, using only the package name. 56 | // (By contrast, [types.RelativeTo] uses the complete package path, 57 | // which is often excessive.) 58 | // 59 | // If pkg is nil, it is equivalent to [*types.Package.Name]. 60 | func NameRelativeTo(pkg *types.Package) types.Qualifier { 61 | return func(other *types.Package) string { 62 | if pkg != nil && pkg == other { 63 | return "" // same package; unqualified 64 | } 65 | return other.Name() 66 | } 67 | } 68 | 69 | // A NamedOrAlias is a [types.Type] that is named (as 70 | // defined by the spec) and capable of bearing type parameters: it 71 | // abstracts aliases ([types.Alias]) and defined types 72 | // ([types.Named]). 73 | // 74 | // Every type declared by an explicit "type" declaration is a 75 | // NamedOrAlias. (Built-in type symbols may additionally 76 | // have type [types.Basic], which is not a NamedOrAlias, 77 | // though the spec regards them as "named".) 78 | // 79 | // NamedOrAlias cannot expose the Origin method, because 80 | // [types.Alias.Origin] and [types.Named.Origin] have different 81 | // (covariant) result types; use [Origin] instead. 82 | type NamedOrAlias interface { 83 | types.Type 84 | Obj() *types.TypeName 85 | } 86 | 87 | // TypeParams is a light shim around t.TypeParams(). 88 | // (go/types.Alias).TypeParams requires >= 1.23. 89 | func TypeParams(t NamedOrAlias) *types.TypeParamList { 90 | switch t := t.(type) { 91 | case *types.Alias: 92 | return aliases.TypeParams(t) 93 | case *types.Named: 94 | return t.TypeParams() 95 | } 96 | return nil 97 | } 98 | 99 | // TypeArgs is a light shim around t.TypeArgs(). 100 | // (go/types.Alias).TypeArgs requires >= 1.23. 101 | func TypeArgs(t NamedOrAlias) *types.TypeList { 102 | switch t := t.(type) { 103 | case *types.Alias: 104 | return aliases.TypeArgs(t) 105 | case *types.Named: 106 | return t.TypeArgs() 107 | } 108 | return nil 109 | } 110 | 111 | // Origin returns the generic type of the Named or Alias type t if it 112 | // is instantiated, otherwise it returns t. 113 | func Origin(t NamedOrAlias) NamedOrAlias { 114 | switch t := t.(type) { 115 | case *types.Alias: 116 | return aliases.Origin(t) 117 | case *types.Named: 118 | return t.Origin() 119 | } 120 | return t 121 | } 122 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/versions/constraint.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package versions 6 | 7 | import "go/build/constraint" 8 | 9 | // ConstraintGoVersion is constraint.GoVersion (if built with go1.21+). 10 | // Otherwise nil. 11 | // 12 | // Deprecate once x/tools is after go1.21. 13 | var ConstraintGoVersion func(x constraint.Expr) string 14 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/versions/constraint_go121.go: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | //go:build go1.21 6 | // +build go1.21 7 | 8 | package versions 9 | 10 | import "go/build/constraint" 11 | 12 | func init() { 13 | ConstraintGoVersion = constraint.GoVersion 14 | } 15 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/versions/features.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package versions 6 | 7 | // This file contains predicates for working with file versions to 8 | // decide when a tool should consider a language feature enabled. 9 | 10 | // GoVersions that features in x/tools can be gated to. 11 | const ( 12 | Go1_18 = "go1.18" 13 | Go1_19 = "go1.19" 14 | Go1_20 = "go1.20" 15 | Go1_21 = "go1.21" 16 | Go1_22 = "go1.22" 17 | ) 18 | 19 | // Future is an invalid unknown Go version sometime in the future. 20 | // Do not use directly with Compare. 21 | const Future = "" 22 | 23 | // AtLeast reports whether the file version v comes after a Go release. 24 | // 25 | // Use this predicate to enable a behavior once a certain Go release 26 | // has happened (and stays enabled in the future). 27 | func AtLeast(v, release string) bool { 28 | if v == Future { 29 | return true // an unknown future version is always after y. 30 | } 31 | return Compare(Lang(v), Lang(release)) >= 0 32 | } 33 | 34 | // Before reports whether the file version v is strictly before a Go release. 35 | // 36 | // Use this predicate to disable a behavior once a certain Go release 37 | // has happened (and stays enabled in the future). 38 | func Before(v, release string) bool { 39 | if v == Future { 40 | return false // an unknown future version happens after y. 41 | } 42 | return Compare(Lang(v), Lang(release)) < 0 43 | } 44 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/versions/gover.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // This is a fork of internal/gover for use by x/tools until 6 | // go1.21 and earlier are no longer supported by x/tools. 7 | 8 | package versions 9 | 10 | import "strings" 11 | 12 | // A gover is a parsed Go gover: major[.Minor[.Patch]][kind[pre]] 13 | // The numbers are the original decimal strings to avoid integer overflows 14 | // and since there is very little actual math. (Probably overflow doesn't matter in practice, 15 | // but at the time this code was written, there was an existing test that used 16 | // go1.99999999999, which does not fit in an int on 32-bit platforms. 17 | // The "big decimal" representation avoids the problem entirely.) 18 | type gover struct { 19 | major string // decimal 20 | minor string // decimal or "" 21 | patch string // decimal or "" 22 | kind string // "", "alpha", "beta", "rc" 23 | pre string // decimal or "" 24 | } 25 | 26 | // compare returns -1, 0, or +1 depending on whether 27 | // x < y, x == y, or x > y, interpreted as toolchain versions. 28 | // The versions x and y must not begin with a "go" prefix: just "1.21" not "go1.21". 29 | // Malformed versions compare less than well-formed versions and equal to each other. 30 | // The language version "1.21" compares less than the release candidate and eventual releases "1.21rc1" and "1.21.0". 31 | func compare(x, y string) int { 32 | vx := parse(x) 33 | vy := parse(y) 34 | 35 | if c := cmpInt(vx.major, vy.major); c != 0 { 36 | return c 37 | } 38 | if c := cmpInt(vx.minor, vy.minor); c != 0 { 39 | return c 40 | } 41 | if c := cmpInt(vx.patch, vy.patch); c != 0 { 42 | return c 43 | } 44 | if c := strings.Compare(vx.kind, vy.kind); c != 0 { // "" < alpha < beta < rc 45 | return c 46 | } 47 | if c := cmpInt(vx.pre, vy.pre); c != 0 { 48 | return c 49 | } 50 | return 0 51 | } 52 | 53 | // lang returns the Go language version. For example, lang("1.2.3") == "1.2". 54 | func lang(x string) string { 55 | v := parse(x) 56 | if v.minor == "" || v.major == "1" && v.minor == "0" { 57 | return v.major 58 | } 59 | return v.major + "." + v.minor 60 | } 61 | 62 | // isValid reports whether the version x is valid. 63 | func isValid(x string) bool { 64 | return parse(x) != gover{} 65 | } 66 | 67 | // parse parses the Go version string x into a version. 68 | // It returns the zero version if x is malformed. 69 | func parse(x string) gover { 70 | var v gover 71 | 72 | // Parse major version. 73 | var ok bool 74 | v.major, x, ok = cutInt(x) 75 | if !ok { 76 | return gover{} 77 | } 78 | if x == "" { 79 | // Interpret "1" as "1.0.0". 80 | v.minor = "0" 81 | v.patch = "0" 82 | return v 83 | } 84 | 85 | // Parse . before minor version. 86 | if x[0] != '.' { 87 | return gover{} 88 | } 89 | 90 | // Parse minor version. 91 | v.minor, x, ok = cutInt(x[1:]) 92 | if !ok { 93 | return gover{} 94 | } 95 | if x == "" { 96 | // Patch missing is same as "0" for older versions. 97 | // Starting in Go 1.21, patch missing is different from explicit .0. 98 | if cmpInt(v.minor, "21") < 0 { 99 | v.patch = "0" 100 | } 101 | return v 102 | } 103 | 104 | // Parse patch if present. 105 | if x[0] == '.' { 106 | v.patch, x, ok = cutInt(x[1:]) 107 | if !ok || x != "" { 108 | // Note that we are disallowing prereleases (alpha, beta, rc) for patch releases here (x != ""). 109 | // Allowing them would be a bit confusing because we already have: 110 | // 1.21 < 1.21rc1 111 | // But a prerelease of a patch would have the opposite effect: 112 | // 1.21.3rc1 < 1.21.3 113 | // We've never needed them before, so let's not start now. 114 | return gover{} 115 | } 116 | return v 117 | } 118 | 119 | // Parse prerelease. 120 | i := 0 121 | for i < len(x) && (x[i] < '0' || '9' < x[i]) { 122 | if x[i] < 'a' || 'z' < x[i] { 123 | return gover{} 124 | } 125 | i++ 126 | } 127 | if i == 0 { 128 | return gover{} 129 | } 130 | v.kind, x = x[:i], x[i:] 131 | if x == "" { 132 | return v 133 | } 134 | v.pre, x, ok = cutInt(x) 135 | if !ok || x != "" { 136 | return gover{} 137 | } 138 | 139 | return v 140 | } 141 | 142 | // cutInt scans the leading decimal number at the start of x to an integer 143 | // and returns that value and the rest of the string. 144 | func cutInt(x string) (n, rest string, ok bool) { 145 | i := 0 146 | for i < len(x) && '0' <= x[i] && x[i] <= '9' { 147 | i++ 148 | } 149 | if i == 0 || x[0] == '0' && i != 1 { // no digits or unnecessary leading zero 150 | return "", "", false 151 | } 152 | return x[:i], x[i:], true 153 | } 154 | 155 | // cmpInt returns cmp.Compare(x, y) interpreting x and y as decimal numbers. 156 | // (Copied from golang.org/x/mod/semver's compareInt.) 157 | func cmpInt(x, y string) int { 158 | if x == y { 159 | return 0 160 | } 161 | if len(x) < len(y) { 162 | return -1 163 | } 164 | if len(x) > len(y) { 165 | return +1 166 | } 167 | if x < y { 168 | return -1 169 | } else { 170 | return +1 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/versions/types.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package versions 6 | 7 | import ( 8 | "go/ast" 9 | "go/types" 10 | ) 11 | 12 | // FileVersion returns a file's Go version. 13 | // The reported version is an unknown Future version if a 14 | // version cannot be determined. 15 | func FileVersion(info *types.Info, file *ast.File) string { 16 | // In tools built with Go >= 1.22, the Go version of a file 17 | // follow a cascades of sources: 18 | // 1) types.Info.FileVersion, which follows the cascade: 19 | // 1.a) file version (ast.File.GoVersion), 20 | // 1.b) the package version (types.Config.GoVersion), or 21 | // 2) is some unknown Future version. 22 | // 23 | // File versions require a valid package version to be provided to types 24 | // in Config.GoVersion. Config.GoVersion is either from the package's module 25 | // or the toolchain (go run). This value should be provided by go/packages 26 | // or unitchecker.Config.GoVersion. 27 | if v := info.FileVersions[file]; IsValid(v) { 28 | return v 29 | } 30 | // Note: we could instead return runtime.Version() [if valid]. 31 | // This would act as a max version on what a tool can support. 32 | return Future 33 | } 34 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/internal/versions/versions.go: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package versions 6 | 7 | import ( 8 | "strings" 9 | ) 10 | 11 | // Note: If we use build tags to use go/versions when go >=1.22, 12 | // we run into go.dev/issue/53737. Under some operations users would see an 13 | // import of "go/versions" even if they would not compile the file. 14 | // For example, during `go get -u ./...` (go.dev/issue/64490) we do not try to include 15 | // For this reason, this library just a clone of go/versions for the moment. 16 | 17 | // Lang returns the Go language version for version x. 18 | // If x is not a valid version, Lang returns the empty string. 19 | // For example: 20 | // 21 | // Lang("go1.21rc2") = "go1.21" 22 | // Lang("go1.21.2") = "go1.21" 23 | // Lang("go1.21") = "go1.21" 24 | // Lang("go1") = "go1" 25 | // Lang("bad") = "" 26 | // Lang("1.21") = "" 27 | func Lang(x string) string { 28 | v := lang(stripGo(x)) 29 | if v == "" { 30 | return "" 31 | } 32 | return x[:2+len(v)] // "go"+v without allocation 33 | } 34 | 35 | // Compare returns -1, 0, or +1 depending on whether 36 | // x < y, x == y, or x > y, interpreted as Go versions. 37 | // The versions x and y must begin with a "go" prefix: "go1.21" not "1.21". 38 | // Invalid versions, including the empty string, compare less than 39 | // valid versions and equal to each other. 40 | // The language version "go1.21" compares less than the 41 | // release candidate and eventual releases "go1.21rc1" and "go1.21.0". 42 | // Custom toolchain suffixes are ignored during comparison: 43 | // "go1.21.0" and "go1.21.0-bigcorp" are equal. 44 | func Compare(x, y string) int { return compare(stripGo(x), stripGo(y)) } 45 | 46 | // IsValid reports whether the version x is valid. 47 | func IsValid(x string) bool { return isValid(stripGo(x)) } 48 | 49 | // stripGo converts from a "go1.21" version to a "1.21" version. 50 | // If v does not start with "go", stripGo returns the empty string (a known invalid version). 51 | func stripGo(v string) string { 52 | v, _, _ = strings.Cut(v, "-") // strip -bigcorp suffix. 53 | if len(v) < 2 || v[:2] != "go" { 54 | return "" 55 | } 56 | return v[2:] 57 | } 58 | -------------------------------------------------------------------------------- /vendor/golang.org/x/tools/txtar/archive.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package txtar implements a trivial text-based file archive format. 6 | // 7 | // The goals for the format are: 8 | // 9 | // - be trivial enough to create and edit by hand. 10 | // - be able to store trees of text files describing go command test cases. 11 | // - diff nicely in git history and code reviews. 12 | // 13 | // Non-goals include being a completely general archive format, 14 | // storing binary data, storing file modes, storing special files like 15 | // symbolic links, and so on. 16 | // 17 | // # Txtar format 18 | // 19 | // A txtar archive is zero or more comment lines and then a sequence of file entries. 20 | // Each file entry begins with a file marker line of the form "-- FILENAME --" 21 | // and is followed by zero or more file content lines making up the file data. 22 | // The comment or file content ends at the next file marker line. 23 | // The file marker line must begin with the three-byte sequence "-- " 24 | // and end with the three-byte sequence " --", but the enclosed 25 | // file name can be surrounding by additional white space, 26 | // all of which is stripped. 27 | // 28 | // If the txtar file is missing a trailing newline on the final line, 29 | // parsers should consider a final newline to be present anyway. 30 | // 31 | // There are no possible syntax errors in a txtar archive. 32 | package txtar 33 | 34 | import ( 35 | "bytes" 36 | "fmt" 37 | "os" 38 | "strings" 39 | ) 40 | 41 | // An Archive is a collection of files. 42 | type Archive struct { 43 | Comment []byte 44 | Files []File 45 | } 46 | 47 | // A File is a single file in an archive. 48 | type File struct { 49 | Name string // name of file ("foo/bar.txt") 50 | Data []byte // text content of file 51 | } 52 | 53 | // Format returns the serialized form of an Archive. 54 | // It is assumed that the Archive data structure is well-formed: 55 | // a.Comment and all a.File[i].Data contain no file marker lines, 56 | // and all a.File[i].Name is non-empty. 57 | func Format(a *Archive) []byte { 58 | var buf bytes.Buffer 59 | buf.Write(fixNL(a.Comment)) 60 | for _, f := range a.Files { 61 | fmt.Fprintf(&buf, "-- %s --\n", f.Name) 62 | buf.Write(fixNL(f.Data)) 63 | } 64 | return buf.Bytes() 65 | } 66 | 67 | // ParseFile parses the named file as an archive. 68 | func ParseFile(file string) (*Archive, error) { 69 | data, err := os.ReadFile(file) 70 | if err != nil { 71 | return nil, err 72 | } 73 | return Parse(data), nil 74 | } 75 | 76 | // Parse parses the serialized form of an Archive. 77 | // The returned Archive holds slices of data. 78 | func Parse(data []byte) *Archive { 79 | a := new(Archive) 80 | var name string 81 | a.Comment, name, data = findFileMarker(data) 82 | for name != "" { 83 | f := File{name, nil} 84 | f.Data, name, data = findFileMarker(data) 85 | a.Files = append(a.Files, f) 86 | } 87 | return a 88 | } 89 | 90 | var ( 91 | newlineMarker = []byte("\n-- ") 92 | marker = []byte("-- ") 93 | markerEnd = []byte(" --") 94 | ) 95 | 96 | // findFileMarker finds the next file marker in data, 97 | // extracts the file name, and returns the data before the marker, 98 | // the file name, and the data after the marker. 99 | // If there is no next marker, findFileMarker returns before = fixNL(data), name = "", after = nil. 100 | func findFileMarker(data []byte) (before []byte, name string, after []byte) { 101 | var i int 102 | for { 103 | if name, after = isMarker(data[i:]); name != "" { 104 | return data[:i], name, after 105 | } 106 | j := bytes.Index(data[i:], newlineMarker) 107 | if j < 0 { 108 | return fixNL(data), "", nil 109 | } 110 | i += j + 1 // positioned at start of new possible marker 111 | } 112 | } 113 | 114 | // isMarker checks whether data begins with a file marker line. 115 | // If so, it returns the name from the line and the data after the line. 116 | // Otherwise it returns name == "" with an unspecified after. 117 | func isMarker(data []byte) (name string, after []byte) { 118 | if !bytes.HasPrefix(data, marker) { 119 | return "", nil 120 | } 121 | if i := bytes.IndexByte(data, '\n'); i >= 0 { 122 | data, after = data[:i], data[i+1:] 123 | } 124 | if !(bytes.HasSuffix(data, markerEnd) && len(data) >= len(marker)+len(markerEnd)) { 125 | return "", nil 126 | } 127 | return strings.TrimSpace(string(data[len(marker) : len(data)-len(markerEnd)])), after 128 | } 129 | 130 | // If data is empty or ends in \n, fixNL returns data. 131 | // Otherwise fixNL returns a new slice consisting of data with a final \n added. 132 | func fixNL(data []byte) []byte { 133 | if len(data) == 0 || data[len(data)-1] == '\n' { 134 | return data 135 | } 136 | d := make([]byte, len(data)+1) 137 | copy(d, data) 138 | d[len(data)] = '\n' 139 | return d 140 | } 141 | -------------------------------------------------------------------------------- /vendor/modules.txt: -------------------------------------------------------------------------------- 1 | # golang.org/x/mod v0.22.0 2 | ## explicit; go 1.22.0 3 | golang.org/x/mod/internal/lazyregexp 4 | golang.org/x/mod/modfile 5 | golang.org/x/mod/module 6 | golang.org/x/mod/semver 7 | # golang.org/x/sync v0.9.0 8 | ## explicit; go 1.18 9 | golang.org/x/sync/errgroup 10 | # golang.org/x/tools v0.27.0 11 | ## explicit; go 1.22.0 12 | golang.org/x/tools/go/analysis 13 | golang.org/x/tools/go/analysis/analysistest 14 | golang.org/x/tools/go/analysis/internal/analysisflags 15 | golang.org/x/tools/go/analysis/internal/checker 16 | golang.org/x/tools/go/analysis/passes/inspect 17 | golang.org/x/tools/go/analysis/unitchecker 18 | golang.org/x/tools/go/ast/inspector 19 | golang.org/x/tools/go/gcexportdata 20 | golang.org/x/tools/go/packages 21 | golang.org/x/tools/go/types/objectpath 22 | golang.org/x/tools/go/types/typeutil 23 | golang.org/x/tools/internal/aliases 24 | golang.org/x/tools/internal/analysisinternal 25 | golang.org/x/tools/internal/diff 26 | golang.org/x/tools/internal/diff/lcs 27 | golang.org/x/tools/internal/event 28 | golang.org/x/tools/internal/event/core 29 | golang.org/x/tools/internal/event/keys 30 | golang.org/x/tools/internal/event/label 31 | golang.org/x/tools/internal/facts 32 | golang.org/x/tools/internal/gcimporter 33 | golang.org/x/tools/internal/gocommand 34 | golang.org/x/tools/internal/goroot 35 | golang.org/x/tools/internal/packagesinternal 36 | golang.org/x/tools/internal/pkgbits 37 | golang.org/x/tools/internal/robustio 38 | golang.org/x/tools/internal/stdlib 39 | golang.org/x/tools/internal/testenv 40 | golang.org/x/tools/internal/typeparams 41 | golang.org/x/tools/internal/typesinternal 42 | golang.org/x/tools/internal/versions 43 | golang.org/x/tools/txtar 44 | --------------------------------------------------------------------------------