Add golang.org/x/tools modernize static analyzer and fix violations (#15946)

* Ran gopls modernize to fix everything

go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...

* Override rules_go provided dependency for golang.org/x/tools to v0.38.0.

To update this, checked out rules_go, then ran `bazel run //go/tools/releaser -- upgrade-dep -mirror=false org_golang_x_tools` and copied the patches.

* Fix buildtag violations and ignore buildtag violations in external

* Introduce modernize analyzer package.

* Add modernize "any" analyzer.

* Fix violations of any analyzer

* Add modernize "appendclipped" analyzer.

* Fix violations of appendclipped

* Add modernize "bloop" analyzer.

* Add modernize "fmtappendf" analyzer.

* Add modernize "forvar" analyzer.

* Add modernize "mapsloop" analyzer.

* Add modernize "minmax" analyzer.

* Fix violations of minmax analyzer

* Add modernize "omitzero" analyzer.

* Add modernize "rangeint" analyzer.

* Fix violations of rangeint.

* Add modernize "reflecttypefor" analyzer.

* Fix violations of reflecttypefor analyzer.

* Add modernize "slicescontains" analyzer.

* Add modernize "slicessort" analyzer.

* Add modernize "slicesdelete" analyzer. This is disabled by default for now. See https://go.dev/issue/73686.

* Add modernize "stringscutprefix" analyzer.

* Add modernize "stringsbuilder" analyzer.

* Fix violations of stringsbuilder analyzer.

* Add modernize "stringsseq" analyzer.

* Add modernize "testingcontext" analyzer.

* Add modernize "waitgroup" analyzer.

* Changelog fragment

* gofmt

* gazelle

* Add modernize "newexpr" analyzer.

* Disable newexpr until go1.26

* Add more details in WORKSPACE on how to update the override

* @nalepae feedback on min()

* gofmt

* Fix violations of forvar
This commit is contained in:
Preston Van Loon
2025-11-13 19:27:22 -06:00
committed by GitHub
parent f77b78943a
commit 2fd6bd8150
605 changed files with 217475 additions and 2228 deletions

View File

@@ -9,7 +9,7 @@ type copier[T any] interface {
func copySlice[T any, C copier[T]](original []C) []T {
// Create a new slice with the same length as the original
newSlice := make([]T, len(original))
for i := 0; i < len(newSlice); i++ {
for i := range newSlice {
newSlice[i] = original[i].Copy()
}
return newSlice

View File

@@ -25,7 +25,7 @@ func fuzzCopies[T any, C enginev1.Copier[T]](t *testing.T, obj C) {
fuzzer := fuzz.NewWithSeed(0)
amount := 1000
t.Run(fmt.Sprintf("%T", obj), func(t *testing.T) {
for i := 0; i < amount; i++ {
for range amount {
fuzzer.Fuzz(obj) // Populate thing with random values
got := obj.Copy()
require.DeepEqual(t, obj, got)

View File

@@ -80,7 +80,7 @@ type ExecutionBlock struct {
}
func (e *ExecutionBlock) MarshalJSON() ([]byte, error) {
decoded := make(map[string]interface{})
decoded := make(map[string]any)
encodedHeader, err := e.Header.MarshalJSON()
if err != nil {
return nil, err
@@ -110,7 +110,7 @@ func (e *ExecutionBlock) UnmarshalJSON(enc []byte) error {
if err := e.Header.UnmarshalJSON(enc); err != nil {
return err
}
decoded := make(map[string]interface{})
decoded := make(map[string]any)
if err := json.Unmarshal(enc, &decoded); err != nil {
return err
}
@@ -162,7 +162,7 @@ func (e *ExecutionBlock) UnmarshalJSON(enc []byte) error {
// Exit early if there are no transactions stored in the json payload.
return nil
}
txsList, ok := rawTxList.([]interface{})
txsList, ok := rawTxList.([]any)
if !ok {
return errors.Errorf("expected transaction list to be of a slice interface type.")
}
@@ -186,7 +186,7 @@ func (e *ExecutionBlock) UnmarshalJSON(enc []byte) error {
// UnmarshalJSON --
func (b *PayloadIDBytes) UnmarshalJSON(enc []byte) error {
var res [8]byte
if err := hexutil.UnmarshalFixedJSON(reflect.TypeOf(b), enc, res[:]); err != nil {
if err := hexutil.UnmarshalFixedJSON(reflect.TypeFor[*PayloadIDBytes](), enc, res[:]); err != nil {
return err
}
*b = res

View File

@@ -296,7 +296,7 @@ func TestJsonMarshalUnmarshal(t *testing.T) {
enc, err := json.Marshal(want)
require.NoError(t, err)
payloadItems := make(map[string]interface{})
payloadItems := make(map[string]any)
require.NoError(t, json.Unmarshal(enc, &payloadItems))
blockHash := want.Hash()
@@ -351,7 +351,7 @@ func TestJsonMarshalUnmarshal(t *testing.T) {
enc, err := json.Marshal(want)
require.NoError(t, err)
payloadItems := make(map[string]interface{})
payloadItems := make(map[string]any)
require.NoError(t, json.Unmarshal(enc, &payloadItems))
blockHash := want.Hash()
@@ -410,7 +410,7 @@ func TestJsonMarshalUnmarshal(t *testing.T) {
enc, err := json.Marshal(want)
require.NoError(t, err)
payloadItems := make(map[string]interface{})
payloadItems := make(map[string]any)
require.NoError(t, json.Unmarshal(enc, &payloadItems))
tx := gethtypes.NewTransaction(
@@ -478,7 +478,7 @@ func TestJsonMarshalUnmarshal(t *testing.T) {
enc, err := json.Marshal(want)
require.NoError(t, err)
payloadItems := make(map[string]interface{})
payloadItems := make(map[string]any)
require.NoError(t, json.Unmarshal(enc, &payloadItems))
blockHash := want.Hash()
@@ -569,7 +569,7 @@ func TestJsonMarshalUnmarshal(t *testing.T) {
enc, err := json.Marshal(want)
require.NoError(t, err)
payloadItems := make(map[string]interface{})
payloadItems := make(map[string]any)
require.NoError(t, json.Unmarshal(enc, &payloadItems))
blockHash := want.Hash()

View File

@@ -60,7 +60,7 @@ func AggregateDisjointOneBitAtts(atts []ethpb.Att) (ethpb.Att, error) {
}
}
keys := make([]int, len(atts))
for i := 0; i < len(atts); i++ {
for i := range atts {
keys[i] = i
}
idx, err := aggregateAttestations(atts, keys, coverage)

View File

@@ -27,7 +27,7 @@ func MaxCoverAttestationAggregation(atts []ethpb.Att) ([]ethpb.Att, error) {
// In the future this conversion will be redundant, as attestation bitlist will be of a Bitlist64
// type, so incoming `atts` parameters can be used as candidates list directly.
candidates := make([]*bitfield.Bitlist64, len(atts))
for i := 0; i < len(atts); i++ {
for i := range atts {
var err error
candidates[i], err = atts[i].GetAggregationBits().ToBitlist64()
if err != nil {
@@ -114,7 +114,7 @@ func MaxCoverAttestationAggregation(atts []ethpb.Att) ([]ethpb.Att, error) {
// NewMaxCover returns initialized Maximum Coverage problem for attestations aggregation.
func NewMaxCover(atts []*ethpb.Attestation) *aggregation.MaxCoverProblem {
candidates := make([]*aggregation.MaxCoverCandidate, len(atts))
for i := 0; i < len(atts); i++ {
for i := range atts {
candidates[i] = aggregation.NewMaxCoverCandidate(i, &atts[i].AggregationBits)
}
return &aggregation.MaxCoverProblem{Candidates: candidates}
@@ -126,7 +126,7 @@ func (al attList) aggregate(coverage bitfield.Bitlist) (*ethpb.Attestation, erro
return nil, errors.Wrap(ErrInvalidAttestationCount, "cannot aggregate")
}
signs := make([]bls.Signature, len(al))
for i := 0; i < len(al); i++ {
for i := range al {
sig, err := signatureFromBytes(al[i].GetSignature())
if err != nil {
return nil, err

View File

@@ -78,7 +78,7 @@ func BenchmarkMaxCoverProblem_MaxCover(b *testing.B) {
}
b.StartTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
candidates := make([]*aggregation.MaxCoverCandidate, len(bitlists))
for i := 0; i < len(bitlists); i++ {
candidates[i] = aggregation.NewMaxCoverCandidate(i, &bitlists[i])
@@ -98,7 +98,7 @@ func BenchmarkMaxCoverProblem_MaxCover(b *testing.B) {
}
b.StartTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, _, err := aggregation.MaxCover(bitlists, len(bitlists), tt.allowOverlaps)
_ = err
}

View File

@@ -14,7 +14,7 @@ import (
// BitlistWithAllBitsSet creates list of bitlists with all bits set.
func BitlistWithAllBitsSet(length uint64) bitfield.Bitlist {
b := bitfield.NewBitlist(length)
for i := uint64(0); i < length; i++ {
for i := range length {
b.SetBitAt(i, true)
}
return b
@@ -23,7 +23,7 @@ func BitlistWithAllBitsSet(length uint64) bitfield.Bitlist {
// BitlistsWithSingleBitSet creates list of bitlists with a single bit set in each.
func BitlistsWithSingleBitSet(n, length uint64) []bitfield.Bitlist {
lists := make([]bitfield.Bitlist, n)
for i := uint64(0); i < n; i++ {
for i := range n {
b := bitfield.NewBitlist(length)
b.SetBitAt(i%length, true)
lists[i] = b
@@ -34,7 +34,7 @@ func BitlistsWithSingleBitSet(n, length uint64) []bitfield.Bitlist {
// Bitlists64WithSingleBitSet creates list of bitlists with a single bit set in each.
func Bitlists64WithSingleBitSet(n, length uint64) []*bitfield.Bitlist64 {
lists := make([]*bitfield.Bitlist64, n)
for i := uint64(0); i < n; i++ {
for i := range n {
b := bitfield.NewBitlist64(length)
b.SetBitAt(i%length, true)
lists[i] = b
@@ -48,7 +48,7 @@ func BitlistsWithMultipleBitSet(t testing.TB, n, length, count uint64) []bitfiel
t.Logf("bitlistsWithMultipleBitSet random seed: %v", seed)
r := rand.New(rand.NewSource(seed)) // #nosec G404
lists := make([]bitfield.Bitlist, n)
for i := uint64(0); i < n; i++ {
for i := range n {
b := bitfield.NewBitlist(length)
keys := r.Perm(int(length)) // lint:ignore uintcast -- This is safe in test code.
for _, key := range keys[:count] {
@@ -65,7 +65,7 @@ func Bitlists64WithMultipleBitSet(t testing.TB, n, length, count uint64) []*bitf
t.Logf("Bitlists64WithMultipleBitSet random seed: %v", seed)
r := rand.New(rand.NewSource(seed)) // #nosec G404
lists := make([]*bitfield.Bitlist64, n)
for i := uint64(0); i < n; i++ {
for i := range n {
b := bitfield.NewBitlist64(length)
keys := r.Perm(int(length)) // lint:ignore uintcast -- This is safe in test code.
for _, key := range keys[:count] {

View File

@@ -8,7 +8,6 @@ import (
"fmt"
"runtime/debug"
"slices"
"sort"
"github.com/OffchainLabs/go-bitfield"
"github.com/OffchainLabs/prysm/v7/beacon-chain/core/signing"
@@ -45,9 +44,7 @@ func ConvertToIndexed(_ context.Context, attestation ethpb.Att, committees ...[]
return nil, err
}
sort.Slice(attIndices, func(i, j int) bool {
return attIndices[i] < attIndices[j]
})
slices.Sort(attIndices)
if attestation.Version() >= version.Electra {
return &ethpb.IndexedAttestationElectra{

View File

@@ -217,8 +217,7 @@ func BenchmarkAttestingIndices_PartialCommittee(b *testing.B) {
bf := bitfield.Bitlist{0b11111111, 0b11111111, 0b10000111, 0b11111111, 0b100}
committee := []primitives.ValidatorIndex{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, err := attestation.AttestingIndices(&eth.Attestation{AggregationBits: bf}, committee)
require.NoError(b, err)
}
@@ -226,7 +225,7 @@ func BenchmarkAttestingIndices_PartialCommittee(b *testing.B) {
func BenchmarkIsValidAttestationIndices(b *testing.B) {
indices := make([]uint64, params.BeaconConfig().MaxValidatorsPerCommittee)
for i := 0; i < len(indices); i++ {
for i := range indices {
indices[i] = uint64(i)
}
att := &eth.IndexedAttestation{
@@ -237,8 +236,8 @@ func BenchmarkIsValidAttestationIndices(b *testing.B) {
},
Signature: make([]byte, fieldparams.BLSSignatureLength),
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
if err := attestation.IsValidAttestationIndices(b.Context(), att, params.BeaconConfig().MaxValidatorsPerCommittee, params.BeaconConfig().MaxCommitteesPerSlot); err != nil {
require.NoError(b, err)
}
@@ -460,14 +459,14 @@ func BenchmarkAttDataIsEqual(b *testing.B) {
b.Run("fast", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
assert.Equal(b, true, attestation.AttDataIsEqual(attData1, attData2))
}
})
b.Run("proto.Equal", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for b.Loop() {
assert.Equal(b, true, attestation.AttDataIsEqual(attData1, attData2))
}
})

View File

@@ -11,7 +11,7 @@ type copier[T any] interface {
func CopySlice[T any, C copier[T]](original []C) []T {
// Create a new slice with the same length as the original
newSlice := make([]T, len(original))
for i := 0; i < len(newSlice); i++ {
for i := range newSlice {
newSlice[i] = original[i].Copy()
}
return newSlice

View File

@@ -312,7 +312,7 @@ func TestCopyBlindedBeaconBlockBodyDeneb(t *testing.T) {
func bytes(length int) []byte {
b := make([]byte, length)
for i := 0; i < length; i++ {
for i := range length {
b[i] = uint8(rand.Int31n(255) + 1)
}
return b
@@ -382,7 +382,7 @@ func genAttestation() *v1alpha1.Attestation {
func genAttestations(num int) []*v1alpha1.Attestation {
atts := make([]*v1alpha1.Attestation, num)
for i := 0; i < num; i++ {
for i := range num {
atts[i] = genAttestation()
}
return atts
@@ -461,7 +461,7 @@ func genProposerSlashing() *v1alpha1.ProposerSlashing {
func genProposerSlashings(num int) []*v1alpha1.ProposerSlashing {
ps := make([]*v1alpha1.ProposerSlashing, num)
for i := 0; i < num; i++ {
for i := range num {
ps[i] = genProposerSlashing()
}
return ps
@@ -484,7 +484,7 @@ func genIndexedAttestation() *v1alpha1.IndexedAttestation {
func genAttesterSlashings(num int) []*v1alpha1.AttesterSlashing {
as := make([]*v1alpha1.AttesterSlashing, num)
for i := 0; i < num; i++ {
for i := range num {
as[i] = genAttesterSlashing()
}
return as
@@ -525,7 +525,7 @@ func genDeposit() *v1alpha1.Deposit {
func genDeposits(num int) []*v1alpha1.Deposit {
d := make([]*v1alpha1.Deposit, num)
for i := 0; i < num; i++ {
for i := range num {
d[i] = genDeposit()
}
return d
@@ -547,7 +547,7 @@ func genSignedVoluntaryExit() *v1alpha1.SignedVoluntaryExit {
func genSignedVoluntaryExits(num int) []*v1alpha1.SignedVoluntaryExit {
sv := make([]*v1alpha1.SignedVoluntaryExit, num)
for i := 0; i < num; i++ {
for i := range num {
sv[i] = genSignedVoluntaryExit()
}
return sv
@@ -765,7 +765,7 @@ func genBlindedBeaconBlockBodyDeneb() *v1alpha1.BlindedBeaconBlockBodyDeneb {
func getKZGCommitments(n int) [][]byte {
kzgs := make([][]byte, n)
for i := 0; i < n; i++ {
for i := range n {
kzgs[i] = bytes(48)
}
return kzgs
@@ -941,7 +941,7 @@ func genWithdrawal() *enginev1.Withdrawal {
func genBLSToExecutionChanges(num int) []*v1alpha1.SignedBLSToExecutionChange {
changes := make([]*v1alpha1.SignedBLSToExecutionChange, num)
for i := 0; i < num; i++ {
for i := range num {
changes[i] = genBLSToExecutionChange()
}
return changes
@@ -969,7 +969,7 @@ func genAttestationElectra() *v1alpha1.AttestationElectra {
func genAttesterSlashingsElectra(num int) []*v1alpha1.AttesterSlashingElectra {
as := make([]*v1alpha1.AttesterSlashingElectra, num)
for i := 0; i < num; i++ {
for i := range num {
as[i] = genAttesterSlashingElectra()
}
return as
@@ -992,7 +992,7 @@ func genIndexedAttestationElectra() *v1alpha1.IndexedAttestationElectra {
func genAttestationsElectra(num int) []*v1alpha1.AttestationElectra {
atts := make([]*v1alpha1.AttestationElectra, num)
for i := 0; i < num; i++ {
for i := range num {
atts[i] = genAttestationElectra()
}
return atts
@@ -1078,7 +1078,7 @@ func genExecutionRequests() *enginev1.ExecutionRequests {
func genDepositRequests(num int) []*enginev1.DepositRequest {
drs := make([]*enginev1.DepositRequest, num)
for i := 0; i < num; i++ {
for i := range num {
drs[i] = genDepositRequest()
}
return drs
@@ -1096,7 +1096,7 @@ func genDepositRequest() *enginev1.DepositRequest {
func genWithdrawalRequests(num int) []*enginev1.WithdrawalRequest {
wrs := make([]*enginev1.WithdrawalRequest, num)
for i := 0; i < num; i++ {
for i := range num {
wrs[i] = genWithdrawalRequest()
}
return wrs
@@ -1112,7 +1112,7 @@ func genWithdrawalRequest() *enginev1.WithdrawalRequest {
func genConsolidationRequests(num int) []*enginev1.ConsolidationRequest {
crs := make([]*enginev1.ConsolidationRequest, num)
for i := 0; i < num; i++ {
for i := range num {
crs[i] = genConsolidationRequest()
}
return crs

View File

@@ -13,7 +13,7 @@ func fuzzCopies[T any, C eth.Copier[T]](t *testing.T, obj C) {
fuzzer := fuzz.NewWithSeed(0)
amount := 1000
t.Run(fmt.Sprintf("%T", obj), func(t *testing.T) {
for i := 0; i < amount; i++ {
for range amount {
fuzzer.Fuzz(obj) // Populate thing with random values
got := obj.Copy()

View File

@@ -12,7 +12,7 @@ type Metadata interface {
AttnetsBitfield() bitfield.Bitvector64
SyncnetsBitfield() bitfield.Bitvector4
CustodyGroupCount() uint64
InnerObject() interface{}
InnerObject() any
IsNil() bool
Copy() Metadata
ssz.Marshaler

View File

@@ -35,7 +35,7 @@ func TestSSZTagSize(t *testing.T) {
assert.Equal(t, pubKeySize, sizes[0], "Unexpected signature size")
}
func sszTagSizes(i interface{}, fName string) ([]int, error) {
func sszTagSizes(i any, fName string) ([]int, error) {
v := reflect.ValueOf(i)
field, exists := v.Type().FieldByName(fName)
if !exists {
@@ -49,7 +49,7 @@ func sszTagSizes(i interface{}, fName string) ([]int, error) {
items := strings.Split(tag[start+1:], ",")
sizes := make([]int, len(items))
var err error
for i := 0; i < len(items); i++ {
for i := range items {
if items[i] == "?" {
sizes[i] = 0
continue