update to golang.org/x/{crypto,net,text,sync,tools}@latest

This commit is contained in:
Mechiel Lukkien 2024-08-22 20:45:35 +02:00
parent 09b13ed4d5
commit c16162eebc
No known key found for this signature in database
39 changed files with 724 additions and 434 deletions

10
go.mod
View file

@ -14,10 +14,10 @@ require (
github.com/prometheus/client_golang v1.18.0
github.com/russross/blackfriday/v2 v2.1.0
go.etcd.io/bbolt v1.3.11
golang.org/x/crypto v0.22.0
golang.org/x/crypto v0.26.0
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f
golang.org/x/net v0.24.0
golang.org/x/text v0.14.0
golang.org/x/net v0.28.0
golang.org/x/text v0.17.0
rsc.io/qr v0.2.0
)
@ -30,8 +30,8 @@ require (
github.com/prometheus/common v0.45.0 // indirect
github.com/prometheus/procfs v0.12.0 // indirect
golang.org/x/mod v0.20.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/tools v0.20.0 // indirect
golang.org/x/tools v0.24.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
)

24
go.sum
View file

@ -16,8 +16,8 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
@ -73,8 +73,8 @@ go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
@ -83,13 +83,13 @@ golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@ -97,11 +97,11 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.20.0 h1:hz/CVckiOxybQvFw6h7b/q80NTr9IUQb4s1IIzW7KNY=
golang.org/x/tools v0.20.0/go.mod h1:WvitBU7JJf6A4jOdg4S1tviW9bhUxkgeCui/0JHctQg=
golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24=
golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

4
vendor/golang.org/x/crypto/LICENSE generated vendored
View file

@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

View file

@ -15,6 +15,7 @@ import (
"io"
"math/big"
"net/http"
"runtime/debug"
"strconv"
"strings"
"time"
@ -271,9 +272,27 @@ func (c *Client) httpClient() *http.Client {
}
// packageVersion is the version of the module that contains this package, for
// sending as part of the User-Agent header. It's set in version_go112.go.
// sending as part of the User-Agent header.
var packageVersion string
func init() {
// Set packageVersion if the binary was built in modules mode and x/crypto
// was not replaced with a different module.
info, ok := debug.ReadBuildInfo()
if !ok {
return
}
for _, m := range info.Deps {
if m.Path != "golang.org/x/crypto" {
continue
}
if m.Replace == nil {
packageVersion = m.Version
}
break
}
}
// userAgent returns the User-Agent header value. It includes the package name,
// the module version (if available), and the c.UserAgent value (if set).
func (c *Client) userAgent() string {

View file

@ -1,27 +0,0 @@
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.12
package acme
import "runtime/debug"
func init() {
// Set packageVersion if the binary was built in modules mode and x/crypto
// was not replaced with a different module.
info, ok := debug.ReadBuildInfo()
if !ok {
return
}
for _, m := range info.Deps {
if m.Path != "golang.org/x/crypto" {
continue
}
if m.Replace == nil {
packageVersion = m.Version
}
break
}
}

View file

@ -4,7 +4,7 @@
// Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing
// algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf
package bcrypt // import "golang.org/x/crypto/bcrypt"
package bcrypt
// The code is a port of Provos and Mazières's C implementation.
import (

View file

@ -11,7 +11,7 @@
// Deprecated: any new system should use AES (from crypto/aes, if necessary in
// an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from
// golang.org/x/crypto/chacha20poly1305).
package blowfish // import "golang.org/x/crypto/blowfish"
package blowfish
// The code is a port of Bruce Schneier's C implementation.
// See https://www.schneier.com/blowfish.html.

View file

@ -16,7 +16,7 @@ Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To
choose, you can pass the `New` functions from the different SHA packages to
pbkdf2.Key.
*/
package pbkdf2 // import "golang.org/x/crypto/pbkdf2"
package pbkdf2
import (
"crypto/hmac"

4
vendor/golang.org/x/net/LICENSE generated vendored
View file

@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

View file

@ -104,7 +104,7 @@ tokenization, and tokenization and tree construction stages of the WHATWG HTML
parsing specification respectively. While the tokenizer parses and normalizes
individual HTML tokens, only the parser constructs the DOM tree from the
tokenized HTML, as described in the tree construction stage of the
specification, dynamically modifying or extending the docuemnt's DOM tree.
specification, dynamically modifying or extending the document's DOM tree.
If your use case requires semantically well-formed HTML documents, as defined by
the WHATWG specification, the parser should be used rather than the tokenizer.

View file

@ -137,9 +137,7 @@ func (p *PerHost) AddNetwork(net *net.IPNet) {
// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of
// "example.com" matches "example.com" and all of its subdomains.
func (p *PerHost) AddZone(zone string) {
if strings.HasSuffix(zone, ".") {
zone = zone[:len(zone)-1]
}
zone = strings.TrimSuffix(zone, ".")
if !strings.HasPrefix(zone, ".") {
zone = "." + zone
}
@ -148,8 +146,6 @@ func (p *PerHost) AddZone(zone string) {
// AddHost specifies a host name that will use the bypass proxy.
func (p *PerHost) AddHost(host string) {
if strings.HasSuffix(host, ".") {
host = host[:len(host)-1]
}
host = strings.TrimSuffix(host, ".")
p.bypassHosts = append(p.bypassHosts, host)
}

View file

@ -16,7 +16,6 @@ import (
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
@ -279,7 +278,7 @@ func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, er
}
}
if header := frame.HeaderReader(); header != nil {
io.Copy(ioutil.Discard, header)
io.Copy(io.Discard, header)
}
switch frame.PayloadType() {
case ContinuationFrame:
@ -294,7 +293,7 @@ func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, er
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return nil, err
}
io.Copy(ioutil.Discard, frame)
io.Copy(io.Discard, frame)
if frame.PayloadType() == PingFrame {
if _, err := handler.WritePong(b[:n]); err != nil {
return nil, err

View file

@ -17,7 +17,6 @@ import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
@ -208,7 +207,7 @@ again:
n, err = ws.frameReader.Read(msg)
if err == io.EOF {
if trailer := ws.frameReader.TrailerReader(); trailer != nil {
io.Copy(ioutil.Discard, trailer)
io.Copy(io.Discard, trailer)
}
ws.frameReader = nil
goto again
@ -330,7 +329,7 @@ func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {
ws.rio.Lock()
defer ws.rio.Unlock()
if ws.frameReader != nil {
_, err = io.Copy(ioutil.Discard, ws.frameReader)
_, err = io.Copy(io.Discard, ws.frameReader)
if err != nil {
return err
}
@ -362,7 +361,7 @@ again:
return ErrFrameTooLarge
}
payloadType := frame.PayloadType()
data, err := ioutil.ReadAll(frame)
data, err := io.ReadAll(frame)
if err != nil {
return err
}

4
vendor/golang.org/x/sync/LICENSE generated vendored
View file

@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

4
vendor/golang.org/x/text/LICENSE generated vendored
View file

@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

4
vendor/golang.org/x/tools/LICENSE generated vendored
View file

@ -1,4 +1,4 @@
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
@ -10,7 +10,7 @@ notice, this list of conditions and the following disclaimer.
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

View file

@ -1,53 +0,0 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package packagesdriver fetches type sizes for go/packages and go/analysis.
package packagesdriver
import (
"context"
"fmt"
"strings"
"golang.org/x/tools/internal/gocommand"
)
func GetSizesForArgsGolist(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (string, string, error) {
inv.Verb = "list"
inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"}
stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv)
var goarch, compiler string
if rawErr != nil {
rawErrMsg := rawErr.Error()
if strings.Contains(rawErrMsg, "cannot find main module") ||
strings.Contains(rawErrMsg, "go.mod file not found") {
// User's running outside of a module.
// All bets are off. Get GOARCH and guess compiler is gc.
// TODO(matloob): Is this a problem in practice?
inv.Verb = "env"
inv.Args = []string{"GOARCH"}
envout, enverr := gocmdRunner.Run(ctx, inv)
if enverr != nil {
return "", "", enverr
}
goarch = strings.TrimSpace(envout.String())
compiler = "gc"
} else if friendlyErr != nil {
return "", "", friendlyErr
} else {
// This should be unreachable, but be defensive
// in case RunRaw's error results are inconsistent.
return "", "", rawErr
}
} else {
fields := strings.Fields(stdout.String())
if len(fields) < 2 {
return "", "", fmt.Errorf("could not parse GOARCH and Go compiler in format \"<GOARCH> <compiler>\":\nstdout: <<%s>>\nstderr: <<%s>>",
stdout.String(), stderr.String())
}
goarch = fields[0]
compiler = fields[1]
}
return compiler, goarch, nil
}

View file

@ -198,14 +198,6 @@ Instead, ssadump no longer requests the runtime package,
but seeks it among the dependencies of the user-specified packages,
and emits an error if it is not found.
Overlays: The Overlay field in the Config allows providing alternate contents
for Go source files, by providing a mapping from file path to contents.
go/packages will pull in new imports added in overlay files when go/packages
is run in LoadImports mode or greater.
Overlay support for the go list driver isn't complete yet: if the file doesn't
exist on disk, it will only be recognized in an overlay if it is a non-test file
and the package would be reported even without the overlay.
Questions & Tasks
- Add GOARCH/GOOS?

View file

@ -34,8 +34,8 @@ type DriverRequest struct {
// Tests specifies whether the patterns should also return test packages.
Tests bool `json:"tests"`
// Overlay maps file paths (relative to the driver's working directory) to the byte contents
// of overlay files.
// Overlay maps file paths (relative to the driver's working directory)
// to the contents of overlay files (see Config.Overlay).
Overlay map[string][]byte `json:"overlay"`
}
@ -119,7 +119,19 @@ func findExternalDriver(cfg *Config) driver {
stderr := new(bytes.Buffer)
cmd := exec.CommandContext(cfg.Context, tool, words...)
cmd.Dir = cfg.Dir
cmd.Env = cfg.Env
// The cwd gets resolved to the real path. On Darwin, where
// /tmp is a symlink, this breaks anything that expects the
// working directory to keep the original path, including the
// go command when dealing with modules.
//
// os.Getwd stdlib has a special feature where if the
// cwd and the PWD are the same node then it trusts
// the PWD, so by setting it in the env for the child
// process we fix up all the paths returned by the go
// command.
//
// (See similar trick in Invocation.run in ../../internal/gocommand/invoke.go)
cmd.Env = append(slicesClip(cfg.Env), "PWD="+cfg.Dir)
cmd.Stdin = bytes.NewReader(req)
cmd.Stdout = buf
cmd.Stderr = stderr
@ -138,3 +150,7 @@ func findExternalDriver(cfg *Config) driver {
return &response, nil
}
}
// slicesClip removes unused capacity from the slice, returning s[:len(s):len(s)].
// TODO(adonovan): use go1.21 slices.Clip.
func slicesClip[S ~[]E, E any](s S) S { return s[:len(s):len(s)] }

View file

@ -21,7 +21,6 @@ import (
"sync"
"unicode"
"golang.org/x/tools/go/internal/packagesdriver"
"golang.org/x/tools/internal/gocommand"
"golang.org/x/tools/internal/packagesinternal"
)
@ -149,7 +148,7 @@ func goListDriver(cfg *Config, patterns ...string) (_ *DriverResponse, err error
if cfg.Mode&NeedTypesSizes != 0 || cfg.Mode&NeedTypes != 0 {
errCh := make(chan error)
go func() {
compiler, arch, err := packagesdriver.GetSizesForArgsGolist(ctx, state.cfgInvocation(), cfg.gocmdRunner)
compiler, arch, err := getSizesForArgs(ctx, state.cfgInvocation(), cfg.gocmdRunner)
response.dr.Compiler = compiler
response.dr.Arch = arch
errCh <- err
@ -841,6 +840,7 @@ func (state *golistState) cfgInvocation() gocommand.Invocation {
Env: cfg.Env,
Logf: cfg.Logf,
WorkingDir: cfg.Dir,
Overlay: cfg.goListOverlayFile,
}
}
@ -849,26 +849,6 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer,
cfg := state.cfg
inv := state.cfgInvocation()
// For Go versions 1.16 and above, `go list` accepts overlays directly via
// the -overlay flag. Set it, if it's available.
//
// The check for "list" is not necessarily required, but we should avoid
// getting the go version if possible.
if verb == "list" {
goVersion, err := state.getGoVersion()
if err != nil {
return nil, err
}
if goVersion >= 16 {
filename, cleanup, err := state.writeOverlays()
if err != nil {
return nil, err
}
defer cleanup()
inv.Overlay = filename
}
}
inv.Verb = verb
inv.Args = args
gocmdRunner := cfg.gocmdRunner
@ -1015,67 +995,6 @@ func (state *golistState) invokeGo(verb string, args ...string) (*bytes.Buffer,
return stdout, nil
}
// OverlayJSON is the format overlay files are expected to be in.
// The Replace map maps from overlaid paths to replacement paths:
// the Go command will forward all reads trying to open
// each overlaid path to its replacement path, or consider the overlaid
// path not to exist if the replacement path is empty.
//
// From golang/go#39958.
type OverlayJSON struct {
Replace map[string]string `json:"replace,omitempty"`
}
// writeOverlays writes out files for go list's -overlay flag, as described
// above.
func (state *golistState) writeOverlays() (filename string, cleanup func(), err error) {
// Do nothing if there are no overlays in the config.
if len(state.cfg.Overlay) == 0 {
return "", func() {}, nil
}
dir, err := os.MkdirTemp("", "gopackages-*")
if err != nil {
return "", nil, err
}
// The caller must clean up this directory, unless this function returns an
// error.
cleanup = func() {
os.RemoveAll(dir)
}
defer func() {
if err != nil {
cleanup()
}
}()
overlays := map[string]string{}
for k, v := range state.cfg.Overlay {
// Create a unique filename for the overlaid files, to avoid
// creating nested directories.
noSeparator := strings.Join(strings.Split(filepath.ToSlash(k), "/"), "")
f, err := os.CreateTemp(dir, fmt.Sprintf("*-%s", noSeparator))
if err != nil {
return "", func() {}, err
}
if _, err := f.Write(v); err != nil {
return "", func() {}, err
}
if err := f.Close(); err != nil {
return "", func() {}, err
}
overlays[k] = f.Name()
}
b, err := json.Marshal(OverlayJSON{Replace: overlays})
if err != nil {
return "", func() {}, err
}
// Write out the overlay file that contains the filepath mappings.
filename = filepath.Join(dir, "overlay.json")
if err := os.WriteFile(filename, b, 0665); err != nil {
return "", func() {}, err
}
return filename, cleanup, nil
}
func containsGoFile(s []string) bool {
for _, f := range s {
if strings.HasSuffix(f, ".go") {
@ -1104,3 +1023,44 @@ func cmdDebugStr(cmd *exec.Cmd) string {
}
return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " "))
}
// getSizesForArgs queries 'go list' for the appropriate
// Compiler and GOARCH arguments to pass to [types.SizesFor].
func getSizesForArgs(ctx context.Context, inv gocommand.Invocation, gocmdRunner *gocommand.Runner) (string, string, error) {
inv.Verb = "list"
inv.Args = []string{"-f", "{{context.GOARCH}} {{context.Compiler}}", "--", "unsafe"}
stdout, stderr, friendlyErr, rawErr := gocmdRunner.RunRaw(ctx, inv)
var goarch, compiler string
if rawErr != nil {
rawErrMsg := rawErr.Error()
if strings.Contains(rawErrMsg, "cannot find main module") ||
strings.Contains(rawErrMsg, "go.mod file not found") {
// User's running outside of a module.
// All bets are off. Get GOARCH and guess compiler is gc.
// TODO(matloob): Is this a problem in practice?
inv.Verb = "env"
inv.Args = []string{"GOARCH"}
envout, enverr := gocmdRunner.Run(ctx, inv)
if enverr != nil {
return "", "", enverr
}
goarch = strings.TrimSpace(envout.String())
compiler = "gc"
} else if friendlyErr != nil {
return "", "", friendlyErr
} else {
// This should be unreachable, but be defensive
// in case RunRaw's error results are inconsistent.
return "", "", rawErr
}
} else {
fields := strings.Fields(stdout.String())
if len(fields) < 2 {
return "", "", fmt.Errorf("could not parse GOARCH and Go compiler in format \"<GOARCH> <compiler>\":\nstdout: <<%s>>\nstderr: <<%s>>",
stdout.String(), stderr.String())
}
goarch = fields[0]
compiler = fields[1]
}
return compiler, goarch, nil
}

View file

@ -37,10 +37,19 @@ import (
// A LoadMode controls the amount of detail to return when loading.
// The bits below can be combined to specify which fields should be
// filled in the result packages.
//
// The zero value is a special case, equivalent to combining
// the NeedName, NeedFiles, and NeedCompiledGoFiles bits.
//
// ID and Errors (if present) will always be filled.
// Load may return more information than requested.
// [Load] may return more information than requested.
//
// Unfortunately there are a number of open bugs related to
// interactions among the LoadMode bits:
// - https://github.com/golang/go/issues/56633
// - https://github.com/golang/go/issues/56677
// - https://github.com/golang/go/issues/58726
// - https://github.com/golang/go/issues/63517
type LoadMode int
const (
@ -66,7 +75,7 @@ const (
// NeedTypes adds Types, Fset, and IllTyped.
NeedTypes
// NeedSyntax adds Syntax.
// NeedSyntax adds Syntax and Fset.
NeedSyntax
// NeedTypesInfo adds TypesInfo.
@ -123,15 +132,21 @@ const (
// A Config specifies details about how packages should be loaded.
// The zero value is a valid configuration.
//
// Calls to Load do not modify this struct.
//
// TODO(adonovan): #67702: this is currently false: in fact,
// calls to [Load] do not modify the public fields of this struct, but
// may modify hidden fields, so concurrent calls to [Load] must not
// use the same Config. But perhaps we should reestablish the
// documented invariant.
type Config struct {
// Mode controls the level of information returned for each package.
Mode LoadMode
// Context specifies the context for the load operation.
// If the context is cancelled, the loader may stop early
// and return an ErrCancelled error.
// If Context is nil, the load cannot be cancelled.
// Cancelling the context may cause [Load] to abort and
// return an error.
Context context.Context
// Logf is the logger for the config.
@ -200,13 +215,23 @@ type Config struct {
// setting Tests may have no effect.
Tests bool
// Overlay provides a mapping of absolute file paths to file contents.
// If the file with the given path already exists, the parser will use the
// alternative file contents provided by the map.
// Overlay is a mapping from absolute file paths to file contents.
//
// Overlays provide incomplete support for when a given file doesn't
// already exist on disk. See the package doc above for more details.
// For each map entry, [Load] uses the alternative file
// contents provided by the overlay mapping instead of reading
// from the file system. This mechanism can be used to enable
// editor-integrated tools to correctly analyze the contents
// of modified but unsaved buffers, for example.
//
// The overlay mapping is passed to the build system's driver
// (see "The driver protocol") so that it too can report
// consistent package metadata about unsaved files. However,
// drivers may vary in their level of support for overlays.
Overlay map[string][]byte
// goListOverlayFile is the JSON file that encodes the Overlay
// mapping, used by 'go list -overlay=...'
goListOverlayFile string
}
// Load loads and returns the Go packages named by the given patterns.
@ -214,8 +239,22 @@ type Config struct {
// Config specifies loading options;
// nil behaves the same as an empty Config.
//
// Load returns an error if any of the patterns was invalid
// as defined by the underlying build system.
// The [Config.Mode] field is a set of bits that determine what kinds
// of information should be computed and returned. Modes that require
// more information tend to be slower. See [LoadMode] for details
// and important caveats. Its zero value is equivalent to
// NeedName | NeedFiles | NeedCompiledGoFiles.
//
// Each call to Load returns a new set of [Package] instances.
// The Packages and their Imports form a directed acyclic graph.
//
// If the [NeedTypes] mode flag was set, each call to Load uses a new
// [types.Importer], so [types.Object] and [types.Type] values from
// different calls to Load must not be mixed as they will have
// inconsistent notions of type identity.
//
// If any of the patterns was invalid as defined by the
// underlying build system, Load returns an error.
// It may return an empty list of packages without an error,
// for instance for an empty expansion of a valid wildcard.
// Errors associated with a particular package are recorded in the
@ -287,6 +326,17 @@ func defaultDriver(cfg *Config, patterns ...string) (*DriverResponse, bool, erro
// (fall through)
}
// go list fallback
//
// Write overlays once, as there are many calls
// to 'go list' (one per chunk plus others too).
overlay, cleanupOverlay, err := gocommand.WriteOverlays(cfg.Overlay)
if err != nil {
return nil, false, err
}
defer cleanupOverlay()
cfg.goListOverlayFile = overlay
response, err := callDriverOnChunks(goListDriver, cfg, chunks)
if err != nil {
return nil, false, err
@ -366,6 +416,9 @@ func mergeResponses(responses ...*DriverResponse) *DriverResponse {
}
// A Package describes a loaded Go package.
//
// It also defines part of the JSON schema of [DriverResponse].
// See the package documentation for an overview.
type Package struct {
// ID is a unique identifier for a package,
// in a syntax provided by the underlying build system.
@ -424,19 +477,30 @@ type Package struct {
// to corresponding loaded Packages.
Imports map[string]*Package
// Module is the module information for the package if it exists.
//
// Note: it may be missing for std and cmd; see Go issue #65816.
Module *Module
// -- The following fields are not part of the driver JSON schema. --
// Types provides type information for the package.
// The NeedTypes LoadMode bit sets this field for packages matching the
// patterns; type information for dependencies may be missing or incomplete,
// unless NeedDeps and NeedImports are also set.
Types *types.Package
//
// Each call to [Load] returns a consistent set of type
// symbols, as defined by the comment at [types.Identical].
// Avoid mixing type information from two or more calls to [Load].
Types *types.Package `json:"-"`
// Fset provides position information for Types, TypesInfo, and Syntax.
// It is set only when Types is set.
Fset *token.FileSet
Fset *token.FileSet `json:"-"`
// IllTyped indicates whether the package or any dependency contains errors.
// It is set only when Types is set.
IllTyped bool
IllTyped bool `json:"-"`
// Syntax is the package's syntax trees, for the files listed in CompiledGoFiles.
//
@ -446,26 +510,28 @@ type Package struct {
//
// Syntax is kept in the same order as CompiledGoFiles, with the caveat that nils are
// removed. If parsing returned nil, Syntax may be shorter than CompiledGoFiles.
Syntax []*ast.File
Syntax []*ast.File `json:"-"`
// TypesInfo provides type information about the package's syntax trees.
// It is set only when Syntax is set.
TypesInfo *types.Info
TypesInfo *types.Info `json:"-"`
// TypesSizes provides the effective size function for types in TypesInfo.
TypesSizes types.Sizes
TypesSizes types.Sizes `json:"-"`
// -- internal --
// forTest is the package under test, if any.
forTest string
// depsErrors is the DepsErrors field from the go list response, if any.
depsErrors []*packagesinternal.PackageError
// module is the module information for the package if it exists.
Module *Module
}
// Module provides module information for a package.
//
// It also defines part of the JSON schema of [DriverResponse].
// See the package documentation for an overview.
type Module struct {
Path string // module path
Version string // module version
@ -598,6 +664,7 @@ func (p *Package) UnmarshalJSON(b []byte) error {
OtherFiles: flat.OtherFiles,
EmbedFiles: flat.EmbedFiles,
EmbedPatterns: flat.EmbedPatterns,
IgnoredFiles: flat.IgnoredFiles,
ExportFile: flat.ExportFile,
}
if len(flat.Imports) > 0 {
@ -854,6 +921,12 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) {
wg.Wait()
}
// If the context is done, return its error and
// throw out [likely] incomplete packages.
if err := ld.Context.Err(); err != nil {
return nil, err
}
result := make([]*Package, len(initial))
for i, lpkg := range initial {
result[i] = lpkg.Package
@ -887,12 +960,14 @@ func (ld *loader) refine(response *DriverResponse) ([]*Package, error) {
}
if ld.requestedMode&NeedTypes == 0 {
ld.pkgs[i].Types = nil
ld.pkgs[i].Fset = nil
ld.pkgs[i].IllTyped = false
}
if ld.requestedMode&NeedSyntax == 0 {
ld.pkgs[i].Syntax = nil
}
if ld.requestedMode&NeedTypes == 0 && ld.requestedMode&NeedSyntax == 0 {
ld.pkgs[i].Fset = nil
}
if ld.requestedMode&NeedTypesInfo == 0 {
ld.pkgs[i].TypesInfo = nil
}
@ -949,6 +1024,14 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) {
lpkg.Types = types.NewPackage(lpkg.PkgPath, lpkg.Name)
lpkg.Fset = ld.Fset
// Start shutting down if the context is done and do not load
// source or export data files.
// Packages that import this one will have ld.Context.Err() != nil.
// ld.Context.Err() will be returned later by refine.
if ld.Context.Err() != nil {
return
}
// Subtle: we populate all Types fields with an empty Package
// before loading export data so that export data processing
// never has to create a types.Package for an indirect dependency,
@ -1068,6 +1151,13 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) {
return
}
// Start shutting down if the context is done and do not type check.
// Packages that import this one will have ld.Context.Err() != nil.
// ld.Context.Err() will be returned later by refine.
if ld.Context.Err() != nil {
return
}
lpkg.TypesInfo = &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
@ -1245,11 +1335,6 @@ func (ld *loader) parseFiles(filenames []string) ([]*ast.File, []error) {
parsed := make([]*ast.File, n)
errors := make([]error, n)
for i, file := range filenames {
if ld.Config.Context.Err() != nil {
parsed[i] = nil
errors[i] = ld.Config.Context.Err()
continue
}
wg.Add(1)
go func(i int, filename string) {
parsed[i], errors[i] = ld.parseFile(filename)
@ -1415,6 +1500,10 @@ func impliedLoadMode(loadMode LoadMode) LoadMode {
// All these things require knowing the import graph.
loadMode |= NeedImports
}
if loadMode&NeedTypes != 0 {
// Types require the GoVersion from Module.
loadMode |= NeedModule
}
return loadMode
}

View file

@ -49,11 +49,20 @@ func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) {
// PrintErrors returns the number of errors printed.
func PrintErrors(pkgs []*Package) int {
var n int
errModules := make(map[*Module]bool)
Visit(pkgs, nil, func(pkg *Package) {
for _, err := range pkg.Errors {
fmt.Fprintln(os.Stderr, err)
n++
}
// Print pkg.Module.Error once if present.
mod := pkg.Module
if mod != nil && mod.Error != nil && !errModules[mod] {
errModules[mod] = true
fmt.Fprintln(os.Stderr, mod.Error.Err)
n++
}
})
return n
}

View file

@ -51,7 +51,7 @@ type Path string
//
// PO package->object Package.Scope.Lookup
// OT object->type Object.Type
// TT type->type Type.{Elem,Key,Params,Results,Underlying} [EKPRU]
// TT type->type Type.{Elem,Key,{,{,Recv}Type}Params,Results,Underlying,Rhs} [EKPRUTrCa]
// TO type->object Type.{At,Field,Method,Obj} [AFMO]
//
// All valid paths start with a package and end at an object
@ -63,8 +63,8 @@ type Path string
// - The only PO operator is Package.Scope.Lookup, which requires an identifier.
// - The only OT operator is Object.Type,
// which we encode as '.' because dot cannot appear in an identifier.
// - The TT operators are encoded as [EKPRUTC];
// one of these (TypeParam) requires an integer operand,
// - The TT operators are encoded as [EKPRUTrCa];
// two of these ({,Recv}TypeParams) require an integer operand,
// which is encoded as a string of decimal digits.
// - The TO operators are encoded as [AFMO];
// three of these (At,Field,Method) require an integer operand,
@ -104,7 +104,9 @@ const (
opResults = 'R' // .Results() (Signature)
opUnderlying = 'U' // .Underlying() (Named)
opTypeParam = 'T' // .TypeParams.At(i) (Named, Signature)
opRecvTypeParam = 'r' // .RecvTypeParams.At(i) (Signature)
opConstraint = 'C' // .Constraint() (TypeParam)
opRhs = 'a' // .Rhs() (Alias)
// type->object operators
opAt = 'A' // .At(i) (Tuple)
@ -278,21 +280,26 @@ func (enc *Encoder) For(obj types.Object) (Path, error) {
path = append(path, opType)
T := o.Type()
if alias, ok := T.(*aliases.Alias); ok {
if r := findTypeParam(obj, aliases.TypeParams(alias), path, opTypeParam, nil); r != nil {
return Path(r), nil
}
if r := find(obj, aliases.Rhs(alias), append(path, opRhs), nil); r != nil {
return Path(r), nil
}
if tname.IsAlias() {
// type alias
} else if tname.IsAlias() {
// legacy alias
if r := find(obj, T, path, nil); r != nil {
return Path(r), nil
}
} else {
if named, _ := T.(*types.Named); named != nil {
if r := findTypeParam(obj, named.TypeParams(), path, nil); r != nil {
// generic named type
} else if named, ok := T.(*types.Named); ok {
// defined (named) type
if r := findTypeParam(obj, named.TypeParams(), path, opTypeParam, nil); r != nil {
return Path(r), nil
}
}
// defined (named) type
if r := find(obj, T.Underlying(), append(path, opUnderlying), nil); r != nil {
if r := find(obj, named.Underlying(), append(path, opUnderlying), nil); r != nil {
return Path(r), nil
}
}
@ -462,7 +469,10 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName]
}
return find(obj, T.Elem(), append(path, opElem), seen)
case *types.Signature:
if r := findTypeParam(obj, T.TypeParams(), path, seen); r != nil {
if r := findTypeParam(obj, T.RecvTypeParams(), path, opRecvTypeParam, nil); r != nil {
return r
}
if r := findTypeParam(obj, T.TypeParams(), path, opTypeParam, seen); r != nil {
return r
}
if r := find(obj, T.Params(), append(path, opParams), seen); r != nil {
@ -525,10 +535,10 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName]
panic(T)
}
func findTypeParam(obj types.Object, list *types.TypeParamList, path []byte, seen map[*types.TypeName]bool) []byte {
func findTypeParam(obj types.Object, list *types.TypeParamList, path []byte, op byte, seen map[*types.TypeName]bool) []byte {
for i := 0; i < list.Len(); i++ {
tparam := list.At(i)
path2 := appendOpArg(path, opTypeParam, i)
path2 := appendOpArg(path, op, i)
if r := find(obj, tparam, path2, seen); r != nil {
return r
}
@ -580,10 +590,10 @@ func Object(pkg *types.Package, p Path) (types.Object, error) {
code := suffix[0]
suffix = suffix[1:]
// Codes [AFM] have an integer operand.
// Codes [AFMTr] have an integer operand.
var index int
switch code {
case opAt, opField, opMethod, opTypeParam:
case opAt, opField, opMethod, opTypeParam, opRecvTypeParam:
rest := strings.TrimLeft(suffix, "0123456789")
numerals := suffix[:len(suffix)-len(rest)]
suffix = rest
@ -653,6 +663,16 @@ func Object(pkg *types.Package, p Path) (types.Object, error) {
}
t = named.Underlying()
case opRhs:
if alias, ok := t.(*aliases.Alias); ok {
t = aliases.Rhs(alias)
} else if false && aliases.Enabled() {
// The Enabled check is too expensive, so for now we
// simply assume that aliases are not enabled.
// TODO(adonovan): replace with "if true {" when go1.24 is assured.
return nil, fmt.Errorf("cannot apply %q to %s (got %T, want alias)", code, t, t)
}
case opTypeParam:
hasTypeParams, ok := t.(hasTypeParams) // Named, Signature
if !ok {
@ -664,6 +684,17 @@ func Object(pkg *types.Package, p Path) (types.Object, error) {
}
t = tparams.At(index)
case opRecvTypeParam:
sig, ok := t.(*types.Signature) // Signature
if !ok {
return nil, fmt.Errorf("cannot apply %q to %s (got %T, want signature)", code, t, t)
}
rtparams := sig.RecvTypeParams()
if n := rtparams.Len(); index >= n {
return nil, fmt.Errorf("tuple index %d out of range [0-%d)", index, n)
}
t = rtparams.At(index)
case opConstraint:
tparam, ok := t.(*types.TypeParam)
if !ok {
@ -725,6 +756,10 @@ func Object(pkg *types.Package, p Path) (types.Object, error) {
}
}
if obj == nil {
panic(p) // path does not end in an object-valued operator
}
if obj.Pkg() != pkg {
return nil, fmt.Errorf("path denotes %s, which belongs to a different package", obj)
}

View file

@ -16,10 +16,14 @@ import (
// NewAlias creates a new TypeName in Package pkg that
// is an alias for the type rhs.
//
// When GoVersion>=1.22 and GODEBUG=gotypesalias=1,
// the Type() of the return value is a *types.Alias.
func NewAlias(pos token.Pos, pkg *types.Package, name string, rhs types.Type) *types.TypeName {
if enabled() {
// The enabled parameter determines whether the resulting [TypeName]'s
// type is an [types.Alias]. Its value must be the result of a call to
// [Enabled], which computes the effective value of
// GODEBUG=gotypesalias=... by invoking the type checker. The Enabled
// function is expensive and should be called once per task (e.g.
// package import), not once per call to NewAlias.
func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type) *types.TypeName {
if enabled {
tname := types.NewTypeName(pos, pkg, name, nil)
newAlias(tname, rhs)
return tname

View file

@ -16,15 +16,20 @@ import (
type Alias struct{}
func (*Alias) String() string { panic("unreachable") }
func (*Alias) Underlying() types.Type { panic("unreachable") }
func (*Alias) Obj() *types.TypeName { panic("unreachable") }
func Rhs(alias *Alias) types.Type { panic("unreachable") }
func TypeParams(alias *Alias) *types.TypeParamList { panic("unreachable") }
func SetTypeParams(alias *Alias, tparams []*types.TypeParam) { panic("unreachable") }
func TypeArgs(alias *Alias) *types.TypeList { panic("unreachable") }
func Origin(alias *Alias) *Alias { panic("unreachable") }
// Unalias returns the type t for go <=1.21.
func Unalias(t types.Type) types.Type { return t }
// Always false for go <=1.21. Ignores GODEBUG.
func enabled() bool { return false }
func newAlias(name *types.TypeName, rhs types.Type) *Alias { panic("unreachable") }
// Enabled reports whether [NewAlias] should create [types.Alias] types.
//
// Before go1.22, this function always returns false.
func Enabled() bool { return false }

View file

@ -12,14 +12,58 @@ import (
"go/parser"
"go/token"
"go/types"
"os"
"strings"
"sync"
)
// Alias is an alias of types.Alias.
type Alias = types.Alias
// Rhs returns the type on the right-hand side of the alias declaration.
func Rhs(alias *Alias) types.Type {
if alias, ok := any(alias).(interface{ Rhs() types.Type }); ok {
return alias.Rhs() // go1.23+
}
// go1.22's Alias didn't have the Rhs method,
// so Unalias is the best we can do.
return Unalias(alias)
}
// TypeParams returns the type parameter list of the alias.
func TypeParams(alias *Alias) *types.TypeParamList {
if alias, ok := any(alias).(interface{ TypeParams() *types.TypeParamList }); ok {
return alias.TypeParams() // go1.23+
}
return nil
}
// SetTypeParams sets the type parameters of the alias type.
func SetTypeParams(alias *Alias, tparams []*types.TypeParam) {
if alias, ok := any(alias).(interface {
SetTypeParams(tparams []*types.TypeParam)
}); ok {
alias.SetTypeParams(tparams) // go1.23+
} else if len(tparams) > 0 {
panic("cannot set type parameters of an Alias type in go1.22")
}
}
// TypeArgs returns the type arguments used to instantiate the Alias type.
func TypeArgs(alias *Alias) *types.TypeList {
if alias, ok := any(alias).(interface{ TypeArgs() *types.TypeList }); ok {
return alias.TypeArgs() // go1.23+
}
return nil // empty (go1.22)
}
// Origin returns the generic Alias type of which alias is an instance.
// If alias is not an instance of a generic alias, Origin returns alias.
func Origin(alias *Alias) *Alias {
if alias, ok := any(alias).(interface{ Origin() *types.Alias }); ok {
return alias.Origin() // go1.23+
}
return alias // not an instance of a generic alias (go1.22)
}
// Unalias is a wrapper of types.Unalias.
func Unalias(t types.Type) types.Type { return types.Unalias(t) }
@ -33,40 +77,23 @@ func newAlias(tname *types.TypeName, rhs types.Type) *Alias {
return a
}
// enabled returns true when types.Aliases are enabled.
func enabled() bool {
// Use the gotypesalias value in GODEBUG if set.
godebug := os.Getenv("GODEBUG")
value := -1 // last set value.
for _, f := range strings.Split(godebug, ",") {
switch f {
case "gotypesalias=1":
value = 1
case "gotypesalias=0":
value = 0
}
}
switch value {
case 0:
return false
case 1:
return true
default:
return aliasesDefault()
}
}
// aliasesDefault reports if aliases are enabled by default.
func aliasesDefault() bool {
// Dynamically check if Aliases will be produced from go/types.
aliasesDefaultOnce.Do(func() {
// Enabled reports whether [NewAlias] should create [types.Alias] types.
//
// This function is expensive! Call it sparingly.
func Enabled() bool {
// The only reliable way to compute the answer is to invoke go/types.
// We don't parse the GODEBUG environment variable, because
// (a) it's tricky to do so in a manner that is consistent
// with the godebug package; in particular, a simple
// substring check is not good enough. The value is a
// rightmost-wins list of options. But more importantly:
// (b) it is impossible to detect changes to the effective
// setting caused by os.Setenv("GODEBUG"), as happens in
// many tests. Therefore any attempt to cache the result
// is just incorrect.
fset := token.NewFileSet()
f, _ := parser.ParseFile(fset, "a.go", "package p; type A = int", 0)
pkg, _ := new(types.Config).Check("p", fset, []*ast.File{f}, nil)
_, gotypesaliasDefault = pkg.Scope().Lookup("A").Type().(*types.Alias)
})
return gotypesaliasDefault
_, enabled := pkg.Scope().Lookup("A").Type().(*types.Alias)
return enabled
}
var gotypesaliasDefault bool
var aliasesDefaultOnce sync.Once

View file

@ -1,59 +0,0 @@
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package tag provides the labels used for telemetry throughout gopls.
package tag
import (
"golang.org/x/tools/internal/event/keys"
)
var (
// create the label keys we use
Method = keys.NewString("method", "")
StatusCode = keys.NewString("status.code", "")
StatusMessage = keys.NewString("status.message", "")
RPCID = keys.NewString("id", "")
RPCDirection = keys.NewString("direction", "")
File = keys.NewString("file", "")
Directory = keys.New("directory", "")
URI = keys.New("URI", "")
Package = keys.NewString("package", "") // sorted comma-separated list of Package IDs
PackagePath = keys.NewString("package_path", "")
Query = keys.New("query", "")
Snapshot = keys.NewUInt64("snapshot", "")
Operation = keys.NewString("operation", "")
Position = keys.New("position", "")
Category = keys.NewString("category", "")
PackageCount = keys.NewInt("packages", "")
Files = keys.New("files", "")
Port = keys.NewInt("port", "")
Type = keys.New("type", "")
HoverKind = keys.NewString("hoverkind", "")
NewServer = keys.NewString("new_server", "A new server was added")
EndServer = keys.NewString("end_server", "A server was shut down")
ServerID = keys.NewString("server", "The server ID an event is related to")
Logfile = keys.NewString("logfile", "")
DebugAddress = keys.NewString("debug_address", "")
GoplsPath = keys.NewString("gopls_path", "")
ClientID = keys.NewString("client_id", "")
Level = keys.NewInt("level", "The logging level")
)
var (
// create the stats we measure
Started = keys.NewInt64("started", "Count of started RPCs.")
ReceivedBytes = keys.NewInt64("received_bytes", "Bytes received.") //, unit.Bytes)
SentBytes = keys.NewInt64("sent_bytes", "Bytes sent.") //, unit.Bytes)
Latency = keys.NewFloat64("latency_ms", "Elapsed time in milliseconds") //, unit.Milliseconds)
)
const (
Inbound = "in"
Outbound = "out"
)

View file

@ -21,7 +21,6 @@ import (
"sort"
"strconv"
"strings"
"unsafe"
"golang.org/x/tools/go/types/objectpath"
"golang.org/x/tools/internal/aliases"
@ -529,7 +528,7 @@ func (p *iexporter) doDecl(obj types.Object) {
if alias, ok := t.(*aliases.Alias); ok {
// Preserve materialized aliases,
// even of non-exported types.
t = aliasRHS(alias)
t = aliases.Rhs(alias)
}
w.typ(t, obj.Pkg())
break
@ -1331,19 +1330,3 @@ func (e internalError) Error() string { return "gcimporter: " + string(e) }
func internalErrorf(format string, args ...interface{}) error {
return internalError(fmt.Sprintf(format, args...))
}
// aliasRHS removes exactly one Alias constructor.
func aliasRHS(alias *aliases.Alias) types.Type {
// TODO(adonovan): if proposal #66559 is accepted, this will
// become Alias.RHS(alias). In the meantime, we must punch
// through the drywall.
type go123Alias struct {
_ *types.TypeName
_ *types.TypeParamList
RHS types.Type
_ types.Type
}
var raw *go123Alias
*(**aliases.Alias)(unsafe.Pointer(&raw)) = alias
return raw.RHS
}

View file

@ -210,6 +210,7 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte
p := iimporter{
version: int(version),
ipath: path,
aliases: aliases.Enabled(),
shallow: shallow,
reportf: reportf,
@ -369,6 +370,7 @@ type iimporter struct {
version int
ipath string
aliases bool
shallow bool
reportf ReportFunc // if non-nil, used to report bugs
@ -567,7 +569,7 @@ func (r *importReader) obj(name string) {
// tparams := r.tparamList()
// alias.SetTypeParams(tparams)
// }
r.declare(aliases.NewAlias(pos, r.currPkg, name, typ))
r.declare(aliases.NewAlias(r.p.aliases, pos, r.currPkg, name, typ))
case constTag:
typ, val := r.value()

View file

@ -26,6 +26,7 @@ type pkgReader struct {
ctxt *types.Context
imports map[string]*types.Package // previously imported packages, indexed by path
aliases bool // create types.Alias nodes
// lazily initialized arrays corresponding to the unified IR
// PosBase, Pkg, and Type sections, respectively.
@ -99,6 +100,7 @@ func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[st
ctxt: ctxt,
imports: imports,
aliases: aliases.Enabled(),
posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)),
pkgs: make([]*types.Package, input.NumElems(pkgbits.RelocPkg)),
@ -524,7 +526,7 @@ func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) {
case pkgbits.ObjAlias:
pos := r.pos()
typ := r.typ()
declare(aliases.NewAlias(pos, objPkg, objName, typ))
declare(aliases.NewAlias(r.p.aliases, pos, objPkg, objName, typ))
case pkgbits.ObjConst:
pos := r.pos()

View file

@ -8,12 +8,14 @@ package gocommand
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
@ -25,7 +27,6 @@ import (
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/event/keys"
"golang.org/x/tools/internal/event/label"
"golang.org/x/tools/internal/event/tag"
)
// An Runner will run go command invocations and serialize
@ -55,11 +56,14 @@ func (runner *Runner) initialize() {
// 1.14: go: updating go.mod: existing contents have changed since last read
var modConcurrencyError = regexp.MustCompile(`go:.*go.mod.*contents have changed`)
// verb is an event label for the go command verb.
var verb = keys.NewString("verb", "go command verb")
// event keys for go command invocations
var (
verb = keys.NewString("verb", "go command verb")
directory = keys.NewString("directory", "")
)
func invLabels(inv Invocation) []label.Label {
return []label.Label{verb.Of(inv.Verb), tag.Directory.Of(inv.WorkingDir)}
return []label.Label{verb.Of(inv.Verb), directory.Of(inv.WorkingDir)}
}
// Run is a convenience wrapper around RunRaw.
@ -165,7 +169,9 @@ type Invocation struct {
// TODO(rfindley): remove, in favor of Args.
ModFile string
// If Overlay is set, the go command is invoked with -overlay=Overlay.
// Overlay is the name of the JSON overlay file that describes
// unsaved editor buffers; see [WriteOverlays].
// If set, the go command is invoked with -overlay=Overlay.
// TODO(rfindley): remove, in favor of Args.
Overlay string
@ -194,12 +200,14 @@ func (i *Invocation) runWithFriendlyError(ctx context.Context, stdout, stderr io
return
}
func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error {
log := i.Logf
if log == nil {
log = func(string, ...interface{}) {}
// logf logs if i.Logf is non-nil.
func (i *Invocation) logf(format string, args ...any) {
if i.Logf != nil {
i.Logf(format, args...)
}
}
func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error {
goArgs := []string{i.Verb}
appendModFile := func() {
@ -253,12 +261,15 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error {
waitDelay.Set(reflect.ValueOf(30 * time.Second))
}
// On darwin the cwd gets resolved to the real path, which breaks anything that
// expects the working directory to keep the original path, including the
// The cwd gets resolved to the real path. On Darwin, where
// /tmp is a symlink, this breaks anything that expects the
// working directory to keep the original path, including the
// go command when dealing with modules.
// The Go stdlib has a special feature where if the cwd and the PWD are the
// same node then it trusts the PWD, so by setting it in the env for the child
// process we fix up all the paths returned by the go command.
//
// os.Getwd has a special feature where if the cwd and the PWD
// are the same node then it trusts the PWD, so by setting it
// in the env for the child process we fix up all the paths
// returned by the go command.
if !i.CleanEnv {
cmd.Env = os.Environ()
}
@ -268,7 +279,12 @@ func (i *Invocation) run(ctx context.Context, stdout, stderr io.Writer) error {
cmd.Dir = i.WorkingDir
}
defer func(start time.Time) { log("%s for %v", time.Since(start), cmdDebugStr(cmd)) }(time.Now())
debugStr := cmdDebugStr(cmd)
i.logf("starting %v", debugStr)
start := time.Now()
defer func() {
i.logf("%s for %v", time.Since(start), debugStr)
}()
return runCmdContext(ctx, cmd)
}
@ -349,6 +365,7 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) {
}
}
startTime := time.Now()
err = cmd.Start()
if stdoutW != nil {
// The child process has inherited the pipe file,
@ -375,7 +392,7 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) {
case err := <-resChan:
return err
case <-timer.C:
HandleHangingGoCommand(cmd.Process)
HandleHangingGoCommand(startTime, cmd)
case <-ctx.Done():
}
} else {
@ -409,7 +426,7 @@ func runCmdContext(ctx context.Context, cmd *exec.Cmd) (err error) {
return <-resChan
}
func HandleHangingGoCommand(proc *os.Process) {
func HandleHangingGoCommand(start time.Time, cmd *exec.Cmd) {
switch runtime.GOOS {
case "linux", "darwin", "freebsd", "netbsd":
fmt.Fprintln(os.Stderr, `DETECTED A HANGING GO COMMAND
@ -442,7 +459,7 @@ See golang/go#54461 for more details.`)
panic(fmt.Sprintf("running %s: %v", listFiles, err))
}
}
panic(fmt.Sprintf("detected hanging go command (pid %d): see golang/go#54461 for more details", proc.Pid))
panic(fmt.Sprintf("detected hanging go command (golang/go#54461); waited %s\n\tcommand:%s\n\tpid:%d", time.Since(start), cmd, cmd.Process.Pid))
}
func cmdDebugStr(cmd *exec.Cmd) string {
@ -466,3 +483,73 @@ func cmdDebugStr(cmd *exec.Cmd) string {
}
return fmt.Sprintf("GOROOT=%v GOPATH=%v GO111MODULE=%v GOPROXY=%v PWD=%v %v", env["GOROOT"], env["GOPATH"], env["GO111MODULE"], env["GOPROXY"], env["PWD"], strings.Join(args, " "))
}
// WriteOverlays writes each value in the overlay (see the Overlay
// field of go/packages.Config) to a temporary file and returns the name
// of a JSON file describing the mapping that is suitable for the "go
// list -overlay" flag.
//
// On success, the caller must call the cleanup function exactly once
// when the files are no longer needed.
func WriteOverlays(overlay map[string][]byte) (filename string, cleanup func(), err error) {
// Do nothing if there are no overlays in the config.
if len(overlay) == 0 {
return "", func() {}, nil
}
dir, err := os.MkdirTemp("", "gocommand-*")
if err != nil {
return "", nil, err
}
// The caller must clean up this directory,
// unless this function returns an error.
// (The cleanup operand of each return
// statement below is ignored.)
defer func() {
cleanup = func() {
os.RemoveAll(dir)
}
if err != nil {
cleanup()
cleanup = nil
}
}()
// Write each map entry to a temporary file.
overlays := make(map[string]string)
for k, v := range overlay {
// Use a unique basename for each file (001-foo.go),
// to avoid creating nested directories.
base := fmt.Sprintf("%d-%s", 1+len(overlays), filepath.Base(k))
filename := filepath.Join(dir, base)
err := os.WriteFile(filename, v, 0666)
if err != nil {
return "", nil, err
}
overlays[k] = filename
}
// Write the JSON overlay file that maps logical file names to temp files.
//
// OverlayJSON is the format overlay files are expected to be in.
// The Replace map maps from overlaid paths to replacement paths:
// the Go command will forward all reads trying to open
// each overlaid path to its replacement path, or consider the overlaid
// path not to exist if the replacement path is empty.
//
// From golang/go#39958.
type OverlayJSON struct {
Replace map[string]string `json:"replace,omitempty"`
}
b, err := json.Marshal(OverlayJSON{Replace: overlays})
if err != nil {
return "", nil, err
}
filename = filepath.Join(dir, "overlay.json")
if err := os.WriteFile(filename, b, 0666); err != nil {
return "", nil, err
}
return filename, nil, nil
}

View file

@ -107,3 +107,57 @@ func getMainModuleAnd114(ctx context.Context, inv Invocation, r *Runner) (*Modul
}
return mod, lines[4] == "go1.14", nil
}
// WorkspaceVendorEnabled reports whether workspace vendoring is enabled. It takes a *Runner to execute Go commands
// with the supplied context.Context and Invocation. The Invocation can contain pre-defined fields,
// of which only Verb and Args are modified to run the appropriate Go command.
// Inspired by setDefaultBuildMod in modload/init.go
func WorkspaceVendorEnabled(ctx context.Context, inv Invocation, r *Runner) (bool, []*ModuleJSON, error) {
inv.Verb = "env"
inv.Args = []string{"GOWORK"}
stdout, err := r.Run(ctx, inv)
if err != nil {
return false, nil, err
}
goWork := string(bytes.TrimSpace(stdout.Bytes()))
if fi, err := os.Stat(filepath.Join(filepath.Dir(goWork), "vendor")); err == nil && fi.IsDir() {
mainMods, err := getWorkspaceMainModules(ctx, inv, r)
if err != nil {
return false, nil, err
}
return true, mainMods, nil
}
return false, nil, nil
}
// getWorkspaceMainModules gets the main modules' information.
// This is the information needed to figure out if vendoring should be enabled.
func getWorkspaceMainModules(ctx context.Context, inv Invocation, r *Runner) ([]*ModuleJSON, error) {
const format = `{{.Path}}
{{.Dir}}
{{.GoMod}}
{{.GoVersion}}
`
inv.Verb = "list"
inv.Args = []string{"-m", "-f", format}
stdout, err := r.Run(ctx, inv)
if err != nil {
return nil, err
}
lines := strings.Split(strings.TrimSuffix(stdout.String(), "\n"), "\n")
if len(lines) < 4 {
return nil, fmt.Errorf("unexpected stdout: %q", stdout.String())
}
mods := make([]*ModuleJSON, 0, len(lines)/4)
for i := 0; i < len(lines); i += 4 {
mods = append(mods, &ModuleJSON{
Path: lines[i],
Dir: lines[i+1],
GoMod: lines[i+2],
GoVersion: lines[i+3],
Main: true,
})
}
return mods, nil
}

View file

@ -23,6 +23,7 @@ var PackageSymbols = map[string][]Symbol{
{"ErrWriteAfterClose", Var, 0},
{"ErrWriteTooLong", Var, 0},
{"FileInfoHeader", Func, 1},
{"FileInfoNames", Type, 23},
{"Format", Type, 10},
{"FormatGNU", Const, 10},
{"FormatPAX", Const, 10},
@ -820,6 +821,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*ConnectionState).ExportKeyingMaterial", Method, 11},
{"(*Dialer).Dial", Method, 15},
{"(*Dialer).DialContext", Method, 15},
{"(*ECHRejectionError).Error", Method, 23},
{"(*QUICConn).Close", Method, 21},
{"(*QUICConn).ConnectionState", Method, 21},
{"(*QUICConn).HandleData", Method, 21},
@ -827,6 +829,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*QUICConn).SendSessionTicket", Method, 21},
{"(*QUICConn).SetTransportParameters", Method, 21},
{"(*QUICConn).Start", Method, 21},
{"(*QUICConn).StoreSession", Method, 23},
{"(*SessionState).Bytes", Method, 21},
{"(AlertError).Error", Method, 21},
{"(ClientAuthType).String", Method, 15},
@ -877,6 +880,8 @@ var PackageSymbols = map[string][]Symbol{
{"Config.ClientSessionCache", Field, 3},
{"Config.CurvePreferences", Field, 3},
{"Config.DynamicRecordSizingDisabled", Field, 7},
{"Config.EncryptedClientHelloConfigList", Field, 23},
{"Config.EncryptedClientHelloRejectionVerify", Field, 23},
{"Config.GetCertificate", Field, 4},
{"Config.GetClientCertificate", Field, 8},
{"Config.GetConfigForClient", Field, 8},
@ -902,6 +907,7 @@ var PackageSymbols = map[string][]Symbol{
{"ConnectionState", Type, 0},
{"ConnectionState.CipherSuite", Field, 0},
{"ConnectionState.DidResume", Field, 1},
{"ConnectionState.ECHAccepted", Field, 23},
{"ConnectionState.HandshakeComplete", Field, 0},
{"ConnectionState.NegotiatedProtocol", Field, 0},
{"ConnectionState.NegotiatedProtocolIsMutual", Field, 0},
@ -925,6 +931,8 @@ var PackageSymbols = map[string][]Symbol{
{"ECDSAWithP384AndSHA384", Const, 8},
{"ECDSAWithP521AndSHA512", Const, 8},
{"ECDSAWithSHA1", Const, 10},
{"ECHRejectionError", Type, 23},
{"ECHRejectionError.RetryConfigList", Field, 23},
{"Ed25519", Const, 13},
{"InsecureCipherSuites", Func, 14},
{"Listen", Func, 0},
@ -943,6 +951,7 @@ var PackageSymbols = map[string][]Symbol{
{"ParseSessionState", Func, 21},
{"QUICClient", Func, 21},
{"QUICConfig", Type, 21},
{"QUICConfig.EnableStoreSessionEvent", Field, 23},
{"QUICConfig.TLSConfig", Field, 21},
{"QUICConn", Type, 21},
{"QUICEncryptionLevel", Type, 21},
@ -954,16 +963,20 @@ var PackageSymbols = map[string][]Symbol{
{"QUICEvent.Data", Field, 21},
{"QUICEvent.Kind", Field, 21},
{"QUICEvent.Level", Field, 21},
{"QUICEvent.SessionState", Field, 23},
{"QUICEvent.Suite", Field, 21},
{"QUICEventKind", Type, 21},
{"QUICHandshakeDone", Const, 21},
{"QUICNoEvent", Const, 21},
{"QUICRejectedEarlyData", Const, 21},
{"QUICResumeSession", Const, 23},
{"QUICServer", Func, 21},
{"QUICSessionTicketOptions", Type, 21},
{"QUICSessionTicketOptions.EarlyData", Field, 21},
{"QUICSessionTicketOptions.Extra", Field, 23},
{"QUICSetReadSecret", Const, 21},
{"QUICSetWriteSecret", Const, 21},
{"QUICStoreSession", Const, 23},
{"QUICTransportParameters", Const, 21},
{"QUICTransportParametersRequired", Const, 21},
{"QUICWriteData", Const, 21},
@ -1036,6 +1049,8 @@ var PackageSymbols = map[string][]Symbol{
{"(*Certificate).Verify", Method, 0},
{"(*Certificate).VerifyHostname", Method, 0},
{"(*CertificateRequest).CheckSignature", Method, 5},
{"(*OID).UnmarshalBinary", Method, 23},
{"(*OID).UnmarshalText", Method, 23},
{"(*RevocationList).CheckSignatureFrom", Method, 19},
{"(CertificateInvalidError).Error", Method, 0},
{"(ConstraintViolationError).Error", Method, 0},
@ -1043,6 +1058,8 @@ var PackageSymbols = map[string][]Symbol{
{"(InsecureAlgorithmError).Error", Method, 6},
{"(OID).Equal", Method, 22},
{"(OID).EqualASN1OID", Method, 22},
{"(OID).MarshalBinary", Method, 23},
{"(OID).MarshalText", Method, 23},
{"(OID).String", Method, 22},
{"(PublicKeyAlgorithm).String", Method, 10},
{"(SignatureAlgorithm).String", Method, 6},
@ -1196,6 +1213,7 @@ var PackageSymbols = map[string][]Symbol{
{"ParseCertificates", Func, 0},
{"ParseDERCRL", Func, 0},
{"ParseECPrivateKey", Func, 1},
{"ParseOID", Func, 23},
{"ParsePKCS1PrivateKey", Func, 0},
{"ParsePKCS1PublicKey", Func, 10},
{"ParsePKCS8PrivateKey", Func, 0},
@ -2541,6 +2559,7 @@ var PackageSymbols = map[string][]Symbol{
{"PT_NOTE", Const, 0},
{"PT_NULL", Const, 0},
{"PT_OPENBSD_BOOTDATA", Const, 16},
{"PT_OPENBSD_NOBTCFI", Const, 23},
{"PT_OPENBSD_RANDOMIZE", Const, 16},
{"PT_OPENBSD_WXNEEDED", Const, 16},
{"PT_PAX_FLAGS", Const, 16},
@ -3620,13 +3639,16 @@ var PackageSymbols = map[string][]Symbol{
{"STT_COMMON", Const, 0},
{"STT_FILE", Const, 0},
{"STT_FUNC", Const, 0},
{"STT_GNU_IFUNC", Const, 23},
{"STT_HIOS", Const, 0},
{"STT_HIPROC", Const, 0},
{"STT_LOOS", Const, 0},
{"STT_LOPROC", Const, 0},
{"STT_NOTYPE", Const, 0},
{"STT_OBJECT", Const, 0},
{"STT_RELC", Const, 23},
{"STT_SECTION", Const, 0},
{"STT_SRELC", Const, 23},
{"STT_TLS", Const, 0},
{"STV_DEFAULT", Const, 0},
{"STV_HIDDEN", Const, 0},
@ -4544,11 +4566,14 @@ var PackageSymbols = map[string][]Symbol{
{"URLEncoding", Var, 0},
},
"encoding/binary": {
{"Append", Func, 23},
{"AppendByteOrder", Type, 19},
{"AppendUvarint", Func, 19},
{"AppendVarint", Func, 19},
{"BigEndian", Var, 0},
{"ByteOrder", Type, 0},
{"Decode", Func, 23},
{"Encode", Func, 23},
{"LittleEndian", Var, 0},
{"MaxVarintLen16", Const, 0},
{"MaxVarintLen32", Const, 0},
@ -5308,6 +5333,7 @@ var PackageSymbols = map[string][]Symbol{
{"ParenExpr.Rparen", Field, 0},
{"ParenExpr.X", Field, 0},
{"Pkg", Const, 0},
{"Preorder", Func, 23},
{"Print", Func, 0},
{"RECV", Const, 0},
{"RangeStmt", Type, 0},
@ -5898,7 +5924,12 @@ var PackageSymbols = map[string][]Symbol{
},
"go/types": {
{"(*Alias).Obj", Method, 22},
{"(*Alias).Origin", Method, 23},
{"(*Alias).Rhs", Method, 23},
{"(*Alias).SetTypeParams", Method, 23},
{"(*Alias).String", Method, 22},
{"(*Alias).TypeArgs", Method, 23},
{"(*Alias).TypeParams", Method, 23},
{"(*Alias).Underlying", Method, 22},
{"(*ArgumentError).Error", Method, 18},
{"(*ArgumentError).Unwrap", Method, 18},
@ -5943,6 +5974,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*Func).Pkg", Method, 5},
{"(*Func).Pos", Method, 5},
{"(*Func).Scope", Method, 5},
{"(*Func).Signature", Method, 23},
{"(*Func).String", Method, 5},
{"(*Func).Type", Method, 5},
{"(*Info).ObjectOf", Method, 5},
@ -6992,6 +7024,12 @@ var PackageSymbols = map[string][]Symbol{
{"TempFile", Func, 0},
{"WriteFile", Func, 0},
},
"iter": {
{"Pull", Func, 23},
{"Pull2", Func, 23},
{"Seq", Type, 23},
{"Seq2", Type, 23},
},
"log": {
{"(*Logger).Fatal", Method, 0},
{"(*Logger).Fatalf", Method, 0},
@ -7222,11 +7260,16 @@ var PackageSymbols = map[string][]Symbol{
{"Writer", Type, 0},
},
"maps": {
{"All", Func, 23},
{"Clone", Func, 21},
{"Collect", Func, 23},
{"Copy", Func, 21},
{"DeleteFunc", Func, 21},
{"Equal", Func, 21},
{"EqualFunc", Func, 21},
{"Insert", Func, 23},
{"Keys", Func, 23},
{"Values", Func, 23},
},
"math": {
{"Abs", Func, 0},
@ -7617,6 +7660,7 @@ var PackageSymbols = map[string][]Symbol{
},
"math/rand/v2": {
{"(*ChaCha8).MarshalBinary", Method, 22},
{"(*ChaCha8).Read", Method, 23},
{"(*ChaCha8).Seed", Method, 22},
{"(*ChaCha8).Uint64", Method, 22},
{"(*ChaCha8).UnmarshalBinary", Method, 22},
@ -7636,6 +7680,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*Rand).NormFloat64", Method, 22},
{"(*Rand).Perm", Method, 22},
{"(*Rand).Shuffle", Method, 22},
{"(*Rand).Uint", Method, 23},
{"(*Rand).Uint32", Method, 22},
{"(*Rand).Uint32N", Method, 22},
{"(*Rand).Uint64", Method, 22},
@ -7663,6 +7708,7 @@ var PackageSymbols = map[string][]Symbol{
{"Rand", Type, 22},
{"Shuffle", Func, 22},
{"Source", Type, 22},
{"Uint", Func, 23},
{"Uint32", Func, 22},
{"Uint32N", Func, 22},
{"Uint64", Func, 22},
@ -7743,6 +7789,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*DNSError).Error", Method, 0},
{"(*DNSError).Temporary", Method, 0},
{"(*DNSError).Timeout", Method, 0},
{"(*DNSError).Unwrap", Method, 23},
{"(*Dialer).Dial", Method, 1},
{"(*Dialer).DialContext", Method, 7},
{"(*Dialer).MultipathTCP", Method, 21},
@ -7809,6 +7856,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*TCPConn).RemoteAddr", Method, 0},
{"(*TCPConn).SetDeadline", Method, 0},
{"(*TCPConn).SetKeepAlive", Method, 0},
{"(*TCPConn).SetKeepAliveConfig", Method, 23},
{"(*TCPConn).SetKeepAlivePeriod", Method, 2},
{"(*TCPConn).SetLinger", Method, 0},
{"(*TCPConn).SetNoDelay", Method, 0},
@ -7922,6 +7970,7 @@ var PackageSymbols = map[string][]Symbol{
{"DNSError.IsTimeout", Field, 0},
{"DNSError.Name", Field, 0},
{"DNSError.Server", Field, 0},
{"DNSError.UnwrapErr", Field, 23},
{"DefaultResolver", Var, 8},
{"Dial", Func, 0},
{"DialIP", Func, 0},
@ -7937,6 +7986,7 @@ var PackageSymbols = map[string][]Symbol{
{"Dialer.DualStack", Field, 2},
{"Dialer.FallbackDelay", Field, 5},
{"Dialer.KeepAlive", Field, 3},
{"Dialer.KeepAliveConfig", Field, 23},
{"Dialer.LocalAddr", Field, 1},
{"Dialer.Resolver", Field, 8},
{"Dialer.Timeout", Field, 1},
@ -7989,10 +8039,16 @@ var PackageSymbols = map[string][]Symbol{
{"Interfaces", Func, 0},
{"InvalidAddrError", Type, 0},
{"JoinHostPort", Func, 0},
{"KeepAliveConfig", Type, 23},
{"KeepAliveConfig.Count", Field, 23},
{"KeepAliveConfig.Enable", Field, 23},
{"KeepAliveConfig.Idle", Field, 23},
{"KeepAliveConfig.Interval", Field, 23},
{"Listen", Func, 0},
{"ListenConfig", Type, 11},
{"ListenConfig.Control", Field, 11},
{"ListenConfig.KeepAlive", Field, 13},
{"ListenConfig.KeepAliveConfig", Field, 23},
{"ListenIP", Func, 0},
{"ListenMulticastUDP", Func, 0},
{"ListenPacket", Func, 0},
@ -8081,6 +8137,7 @@ var PackageSymbols = map[string][]Symbol{
{"(*Request).Context", Method, 7},
{"(*Request).Cookie", Method, 0},
{"(*Request).Cookies", Method, 0},
{"(*Request).CookiesNamed", Method, 23},
{"(*Request).FormFile", Method, 0},
{"(*Request).FormValue", Method, 0},
{"(*Request).MultipartReader", Method, 0},
@ -8148,7 +8205,9 @@ var PackageSymbols = map[string][]Symbol{
{"Cookie.HttpOnly", Field, 0},
{"Cookie.MaxAge", Field, 0},
{"Cookie.Name", Field, 0},
{"Cookie.Partitioned", Field, 23},
{"Cookie.Path", Field, 0},
{"Cookie.Quoted", Field, 23},
{"Cookie.Raw", Field, 0},
{"Cookie.RawExpires", Field, 0},
{"Cookie.SameSite", Field, 11},
@ -8225,7 +8284,9 @@ var PackageSymbols = map[string][]Symbol{
{"NoBody", Var, 8},
{"NotFound", Func, 0},
{"NotFoundHandler", Func, 0},
{"ParseCookie", Func, 23},
{"ParseHTTPVersion", Func, 0},
{"ParseSetCookie", Func, 23},
{"ParseTime", Func, 1},
{"Post", Func, 0},
{"PostForm", Func, 0},
@ -8252,6 +8313,7 @@ var PackageSymbols = map[string][]Symbol{
{"Request.Host", Field, 0},
{"Request.Method", Field, 0},
{"Request.MultipartForm", Field, 0},
{"Request.Pattern", Field, 23},
{"Request.PostForm", Field, 1},
{"Request.Proto", Field, 0},
{"Request.ProtoMajor", Field, 0},
@ -8453,6 +8515,7 @@ var PackageSymbols = map[string][]Symbol{
{"DefaultRemoteAddr", Const, 0},
{"NewRecorder", Func, 0},
{"NewRequest", Func, 7},
{"NewRequestWithContext", Func, 23},
{"NewServer", Func, 0},
{"NewTLSServer", Func, 0},
{"NewUnstartedServer", Func, 0},
@ -8917,6 +8980,7 @@ var PackageSymbols = map[string][]Symbol{
{"Chown", Func, 0},
{"Chtimes", Func, 0},
{"Clearenv", Func, 0},
{"CopyFS", Func, 23},
{"Create", Func, 0},
{"CreateTemp", Func, 16},
{"DevNull", Const, 0},
@ -9150,6 +9214,7 @@ var PackageSymbols = map[string][]Symbol{
{"IsLocal", Func, 20},
{"Join", Func, 0},
{"ListSeparator", Const, 0},
{"Localize", Func, 23},
{"Match", Func, 0},
{"Rel", Func, 0},
{"Separator", Const, 0},
@ -9232,6 +9297,8 @@ var PackageSymbols = map[string][]Symbol{
{"(Value).Pointer", Method, 0},
{"(Value).Recv", Method, 0},
{"(Value).Send", Method, 0},
{"(Value).Seq", Method, 23},
{"(Value).Seq2", Method, 23},
{"(Value).Set", Method, 0},
{"(Value).SetBool", Method, 0},
{"(Value).SetBytes", Method, 0},
@ -9314,6 +9381,7 @@ var PackageSymbols = map[string][]Symbol{
{"SelectSend", Const, 1},
{"SendDir", Const, 0},
{"Slice", Const, 0},
{"SliceAt", Func, 23},
{"SliceHeader", Type, 0},
{"SliceHeader.Cap", Field, 0},
{"SliceHeader.Data", Field, 0},
@ -9655,6 +9723,7 @@ var PackageSymbols = map[string][]Symbol{
{"BuildSetting", Type, 18},
{"BuildSetting.Key", Field, 18},
{"BuildSetting.Value", Field, 18},
{"CrashOptions", Type, 23},
{"FreeOSMemory", Func, 1},
{"GCStats", Type, 1},
{"GCStats.LastGC", Field, 1},
@ -9672,6 +9741,7 @@ var PackageSymbols = map[string][]Symbol{
{"PrintStack", Func, 0},
{"ReadBuildInfo", Func, 12},
{"ReadGCStats", Func, 1},
{"SetCrashOutput", Func, 23},
{"SetGCPercent", Func, 1},
{"SetMaxStack", Func, 2},
{"SetMaxThreads", Func, 2},
@ -9742,10 +9812,15 @@ var PackageSymbols = map[string][]Symbol{
{"WithRegion", Func, 11},
},
"slices": {
{"All", Func, 23},
{"AppendSeq", Func, 23},
{"Backward", Func, 23},
{"BinarySearch", Func, 21},
{"BinarySearchFunc", Func, 21},
{"Chunk", Func, 23},
{"Clip", Func, 21},
{"Clone", Func, 21},
{"Collect", Func, 23},
{"Compact", Func, 21},
{"CompactFunc", Func, 21},
{"Compare", Func, 21},
@ -9767,11 +9842,16 @@ var PackageSymbols = map[string][]Symbol{
{"MaxFunc", Func, 21},
{"Min", Func, 21},
{"MinFunc", Func, 21},
{"Repeat", Func, 23},
{"Replace", Func, 21},
{"Reverse", Func, 21},
{"Sort", Func, 21},
{"SortFunc", Func, 21},
{"SortStableFunc", Func, 21},
{"Sorted", Func, 23},
{"SortedFunc", Func, 23},
{"SortedStableFunc", Func, 23},
{"Values", Func, 23},
},
"sort": {
{"(Float64Slice).Len", Method, 0},
@ -9936,10 +10016,14 @@ var PackageSymbols = map[string][]Symbol{
{"TrimSpace", Func, 0},
{"TrimSuffix", Func, 1},
},
"structs": {
{"HostLayout", Type, 23},
},
"sync": {
{"(*Cond).Broadcast", Method, 0},
{"(*Cond).Signal", Method, 0},
{"(*Cond).Wait", Method, 0},
{"(*Map).Clear", Method, 23},
{"(*Map).CompareAndDelete", Method, 20},
{"(*Map).CompareAndSwap", Method, 20},
{"(*Map).Delete", Method, 9},
@ -9986,13 +10070,17 @@ var PackageSymbols = map[string][]Symbol{
{"(*Bool).Store", Method, 19},
{"(*Bool).Swap", Method, 19},
{"(*Int32).Add", Method, 19},
{"(*Int32).And", Method, 23},
{"(*Int32).CompareAndSwap", Method, 19},
{"(*Int32).Load", Method, 19},
{"(*Int32).Or", Method, 23},
{"(*Int32).Store", Method, 19},
{"(*Int32).Swap", Method, 19},
{"(*Int64).Add", Method, 19},
{"(*Int64).And", Method, 23},
{"(*Int64).CompareAndSwap", Method, 19},
{"(*Int64).Load", Method, 19},
{"(*Int64).Or", Method, 23},
{"(*Int64).Store", Method, 19},
{"(*Int64).Swap", Method, 19},
{"(*Pointer).CompareAndSwap", Method, 19},
@ -10000,18 +10088,24 @@ var PackageSymbols = map[string][]Symbol{
{"(*Pointer).Store", Method, 19},
{"(*Pointer).Swap", Method, 19},
{"(*Uint32).Add", Method, 19},
{"(*Uint32).And", Method, 23},
{"(*Uint32).CompareAndSwap", Method, 19},
{"(*Uint32).Load", Method, 19},
{"(*Uint32).Or", Method, 23},
{"(*Uint32).Store", Method, 19},
{"(*Uint32).Swap", Method, 19},
{"(*Uint64).Add", Method, 19},
{"(*Uint64).And", Method, 23},
{"(*Uint64).CompareAndSwap", Method, 19},
{"(*Uint64).Load", Method, 19},
{"(*Uint64).Or", Method, 23},
{"(*Uint64).Store", Method, 19},
{"(*Uint64).Swap", Method, 19},
{"(*Uintptr).Add", Method, 19},
{"(*Uintptr).And", Method, 23},
{"(*Uintptr).CompareAndSwap", Method, 19},
{"(*Uintptr).Load", Method, 19},
{"(*Uintptr).Or", Method, 23},
{"(*Uintptr).Store", Method, 19},
{"(*Uintptr).Swap", Method, 19},
{"(*Value).CompareAndSwap", Method, 17},
@ -10023,6 +10117,11 @@ var PackageSymbols = map[string][]Symbol{
{"AddUint32", Func, 0},
{"AddUint64", Func, 0},
{"AddUintptr", Func, 0},
{"AndInt32", Func, 23},
{"AndInt64", Func, 23},
{"AndUint32", Func, 23},
{"AndUint64", Func, 23},
{"AndUintptr", Func, 23},
{"Bool", Type, 19},
{"CompareAndSwapInt32", Func, 0},
{"CompareAndSwapInt64", Func, 0},
@ -10038,6 +10137,11 @@ var PackageSymbols = map[string][]Symbol{
{"LoadUint32", Func, 0},
{"LoadUint64", Func, 0},
{"LoadUintptr", Func, 0},
{"OrInt32", Func, 23},
{"OrInt64", Func, 23},
{"OrUint32", Func, 23},
{"OrUint64", Func, 23},
{"OrUintptr", Func, 23},
{"Pointer", Type, 19},
{"StoreInt32", Func, 0},
{"StoreInt64", Func, 0},
@ -16200,6 +16304,7 @@ var PackageSymbols = map[string][]Symbol{
{"WSAEACCES", Const, 2},
{"WSAECONNABORTED", Const, 9},
{"WSAECONNRESET", Const, 3},
{"WSAENOPROTOOPT", Const, 23},
{"WSAEnumProtocols", Func, 2},
{"WSAID_CONNECTEX", Var, 1},
{"WSAIoctl", Func, 0},
@ -17284,6 +17389,7 @@ var PackageSymbols = map[string][]Symbol{
{"Encode", Func, 0},
{"EncodeRune", Func, 0},
{"IsSurrogate", Func, 0},
{"RuneLen", Func, 23},
},
"unicode/utf8": {
{"AppendRune", Func, 18},
@ -17306,6 +17412,11 @@ var PackageSymbols = map[string][]Symbol{
{"ValidRune", Func, 1},
{"ValidString", Func, 0},
},
"unique": {
{"(Handle).Value", Method, 23},
{"Handle", Type, 23},
{"Make", Func, 23},
},
"unsafe": {
{"Add", Func, 0},
{"Alignof", Func, 0},

View file

@ -1449,10 +1449,10 @@ const (
NotAGenericType
// WrongTypeArgCount occurs when a type or function is instantiated with an
// incorrent number of type arguments, including when a generic type or
// incorrect number of type arguments, including when a generic type or
// function is used without instantiation.
//
// Errors inolving failed type inference are assigned other error codes.
// Errors involving failed type inference are assigned other error codes.
//
// Example:
// type T[p any] int

View file

@ -48,3 +48,18 @@ func ReadGo116ErrorData(err types.Error) (code ErrorCode, start, end token.Pos,
}
return ErrorCode(data[0]), token.Pos(data[1]), token.Pos(data[2]), true
}
// NameRelativeTo returns a types.Qualifier that qualifies members of
// all packages other than pkg, using only the package name.
// (By contrast, [types.RelativeTo] uses the complete package path,
// which is often excessive.)
//
// If pkg is nil, it is equivalent to [*types.Package.Name].
func NameRelativeTo(pkg *types.Package) types.Qualifier {
return func(other *types.Package) string {
if pkg != nil && pkg == other {
return "" // same package; unqualified
}
return other.Name()
}
}

View file

@ -0,0 +1,13 @@
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package versions
import "go/build/constraint"
// ConstraintGoVersion is constraint.GoVersion (if built with go1.21+).
// Otherwise nil.
//
// Deprecate once x/tools is after go1.21.
var ConstraintGoVersion func(x constraint.Expr) string

View file

@ -0,0 +1,14 @@
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.21
// +build go1.21
package versions
import "go/build/constraint"
func init() {
ConstraintGoVersion = constraint.GoVersion
}

View file

@ -12,7 +12,7 @@ import (
"go/types"
)
// FileVersions returns a file's Go version.
// FileVersion returns a file's Go version.
// The reported version is an unknown Future version if a
// version cannot be determined.
func FileVersion(info *types.Info, file *ast.File) string {

14
vendor/modules.txt vendored
View file

@ -64,8 +64,8 @@ github.com/russross/blackfriday/v2
# go.etcd.io/bbolt v1.3.11
## explicit; go 1.22
go.etcd.io/bbolt
# golang.org/x/crypto v0.22.0
## explicit; go 1.18
# golang.org/x/crypto v0.26.0
## explicit; go 1.20
golang.org/x/crypto/acme
golang.org/x/crypto/bcrypt
golang.org/x/crypto/blake2b
@ -80,7 +80,7 @@ golang.org/x/mod/internal/lazyregexp
golang.org/x/mod/modfile
golang.org/x/mod/module
golang.org/x/mod/semver
# golang.org/x/net v0.24.0
# golang.org/x/net v0.28.0
## explicit; go 1.18
golang.org/x/net/dns/dnsmessage
golang.org/x/net/html
@ -89,7 +89,7 @@ golang.org/x/net/idna
golang.org/x/net/internal/socks
golang.org/x/net/proxy
golang.org/x/net/websocket
# golang.org/x/sync v0.7.0
# golang.org/x/sync v0.8.0
## explicit; go 1.18
golang.org/x/sync/errgroup
# golang.org/x/sys v0.24.0
@ -97,7 +97,7 @@ golang.org/x/sync/errgroup
golang.org/x/sys/cpu
golang.org/x/sys/unix
golang.org/x/sys/windows
# golang.org/x/text v0.14.0
# golang.org/x/text v0.17.0
## explicit; go 1.18
golang.org/x/text/cases
golang.org/x/text/encoding
@ -123,10 +123,9 @@ golang.org/x/text/transform
golang.org/x/text/unicode/bidi
golang.org/x/text/unicode/norm
golang.org/x/text/width
# golang.org/x/tools v0.20.0
# golang.org/x/tools v0.24.0
## explicit; go 1.19
golang.org/x/tools/go/gcexportdata
golang.org/x/tools/go/internal/packagesdriver
golang.org/x/tools/go/packages
golang.org/x/tools/go/types/objectpath
golang.org/x/tools/internal/aliases
@ -134,7 +133,6 @@ golang.org/x/tools/internal/event
golang.org/x/tools/internal/event/core
golang.org/x/tools/internal/event/keys
golang.org/x/tools/internal/event/label
golang.org/x/tools/internal/event/tag
golang.org/x/tools/internal/gcimporter
golang.org/x/tools/internal/gocommand
golang.org/x/tools/internal/packagesinternal