Skip to content

Commit

Permalink
*: improve for loop syntax
Browse files Browse the repository at this point in the history
Mostly it's about Go 1.22+ syntax with ranging over integers, but it also
prefers ranging over slices where possible (it makes code a little better to
read).

Notice that we have a number of dangerous loops where slices are mutated
during loop execution, many of these can't be converted since we need proper
length evalutation at every iteration.

Signed-off-by: Roman Khimov <[email protected]>
  • Loading branch information
roman-khimov committed Aug 30, 2024
1 parent 133cd1d commit 1b83dc2
Show file tree
Hide file tree
Showing 113 changed files with 267 additions and 267 deletions.
2 changes: 1 addition & 1 deletion cli/nep_test/nep17_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func TestNEP17Balance(t *testing.T) {

e.CheckNextLine(t, "^Account "+testcli.TestWalletMultiAccount1)
// The order of assets is undefined.
for i := 0; i < 2; i++ {
for range 2 {
line := e.GetNextLine(t)
if strings.Contains(line, "GAS") {
e.CheckLine(t, line, "^\\s*GAS:\\s+GasToken \\("+e.Chain.UtilityTokenHash().StringLE()+"\\)")
Expand Down
6 changes: 3 additions & 3 deletions cli/wallet/nep17.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ func getMatchingTokenRPC(ctx *cli.Context, c *rpcclient.Client, addr util.Uint16
func getMatchingTokenAux(ctx *cli.Context, get func(i int) *wallet.Token, n int, name string, standard string) (*wallet.Token, error) {
var token *wallet.Token
var count int
for i := 0; i < n; i++ {
for i := range n {
t := get(i)
if t != nil && (t.Hash.StringLE() == name || t.Address() == name || t.Symbol == name || t.Name == name) && t.Standard == standard {
if count == 1 {
Expand Down Expand Up @@ -540,7 +540,7 @@ func multiTransferNEP17(ctx *cli.Context) error {
recipients []transferTarget
cosignersSepPos = ctx.NArg() // `--` position.
)
for i := 0; i < ctx.NArg(); i++ {
for i := range ctx.NArg() {
arg := ctx.Args().Get(i)
if arg == cmdargs.CosignersSeparator {
cosignersSepPos = i
Expand All @@ -561,7 +561,7 @@ func multiTransferNEP17(ctx *cli.Context) error {
}

cache := make(map[string]*wallet.Token)
for i := 0; i < cosignersSepPos; i++ {
for i := range cosignersSepPos {
arg := ctx.Args().Get(i)
ss := strings.SplitN(arg, ":", 3)
if len(ss) != 3 {
Expand Down
4 changes: 2 additions & 2 deletions cli/wallet/wallet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1062,7 +1062,7 @@ func TestWalletDumpKeys(t *testing.T) {
e.CheckNextLine(t, pubRegex)
e.CheckNextLine(t, "^\\s*$")
e.CheckNextLine(t, "NVTiAjNgagDkTr5HTzDmQP9kPwPHN5BgVq")
for i := 0; i < 4; i++ {
for range 4 {
e.CheckNextLine(t, pubRegex)
}
e.CheckNextLine(t, "^\\s*$")
Expand All @@ -1085,7 +1085,7 @@ func TestWalletDumpKeys(t *testing.T) {
cmd := append(cmd, "-a", "NVTiAjNgagDkTr5HTzDmQP9kPwPHN5BgVq")
e.Run(t, cmd...)
e.CheckNextLine(t, "3 out of 4 multisig contract")
for i := 0; i < 4; i++ {
for range 4 {
e.CheckNextLine(t, pubRegex)
}
e.CheckEOF(t)
Expand Down
2 changes: 1 addition & 1 deletion examples/nft-nd-nns/nns_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func TestRegisterAndRenew(t *testing.T) {
c.InvokeWithFeeFail(t, "GAS limit exceeded", defaultNameServiceSysfee, "register", "neo.org", e.CommitteeHash)
c.InvokeWithFeeFail(t, "GAS limit exceeded", defaultNameServiceDomainPrice, "register", "neo.com", e.CommitteeHash)
var maxLenFragment string
for i := 0; i < maxDomainNameFragmentLength; i++ {
for i := range maxDomainNameFragmentLength {
maxLenFragment += "q"
}
c.Invoke(t, true, "isAvailable", maxLenFragment+".com")
Expand Down
2 changes: 1 addition & 1 deletion examples/zkp/cubic_circuit/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ func setup(t *testing.T, ccs constraint.ConstraintSystem, phase1ResponsePath str
// receive a []byte, deserialize it, add his contribution and send back to
// coordinator, like it is done in https://github.com/bnb-chain/zkbnb-setup
// for BN254 elliptic curve.
for i := 0; i < nContributionsPhase2; i++ {
for i := range nContributionsPhase2 {
srs2.Contribute()
}

Expand Down
2 changes: 1 addition & 1 deletion internal/basicchain/testdata/storage/storage_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var valuesPrefix = []byte{0x01}
func _deploy(data any, isUpdate bool) {
if !isUpdate {
ctx := storage.GetContext()
for i := 0; i < valuesCount; i++ {
for i := range valuesCount {
key := append(valuesPrefix, byte(i))
storage.Put(ctx, key, i)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/testchain/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func CommitteeAddress() string {
// Sign signs data by all consensus nodes and returns invocation script.
func Sign(h hash.Hashable) []byte {
buf := io.NewBufBinWriter()
for i := 0; i < 3; i++ {
for i := range 3 {
pKey := PrivateKey(i)
sig := pKey.SignHashable(uint32(Network()), h)
if len(sig) != 64 {
Expand Down
2 changes: 1 addition & 1 deletion internal/testcli/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ func (e *Executor) CheckTxTestInvokeOutput(t *testing.T, scriptSize int) {

func (e *Executor) CheckScriptDump(t *testing.T, scriptSize int) {
e.CheckNextLine(t, `INDEX\s+`)
for i := 0; i < scriptSize; i++ {
for range scriptSize {
e.CheckNextLine(t, `\d+\s+\w+`)
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/compiler/analysis.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func isExprNil(e ast.Expr) bool {
// indexOfStruct returns the index of the given field inside that struct.
// If the struct does not contain that field, it will return -1.
func indexOfStruct(strct *types.Struct, fldName string) int {
for i := 0; i < strct.NumFields(); i++ {
for i := range strct.NumFields() {
if strct.Field(i).Name() == fldName {
return i
}
Expand Down
14 changes: 7 additions & 7 deletions pkg/compiler/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ func (c *codegen) isVerifyFunc(decl *ast.FuncDecl) bool {
}

func (c *codegen) clearSlots(n int) {
for i := 0; i < n; i++ {
for i := range n {
emit.Opcodes(c.prog.BinWriter, opcode.PUSHNULL)
c.emitStoreByIndex(varLocal, i)
}
Expand Down Expand Up @@ -680,7 +680,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
ast.Walk(c, n.Rhs[0])
c.emitToken(n.Tok, c.typeOf(n.Rhs[0]))
}
for i := 0; i < len(n.Lhs); i++ {
for i := range n.Lhs {
switch t := n.Lhs[i].(type) {
case *ast.Ident:
if n.Tok == token.DEFINE {
Expand Down Expand Up @@ -1099,7 +1099,7 @@ func (c *codegen) Visit(node ast.Node) ast.Visitor {
f := c.typeOf(n.Fun).Underlying().(*types.Signature)
sz = f.Results().Len()
}
for i := 0; i < sz; i++ {
for range sz {
emit.Opcodes(c.prog.BinWriter, opcode.DROP)
}
}
Expand Down Expand Up @@ -1662,7 +1662,7 @@ func (c *codegen) dropStackLabel() {

func (c *codegen) dropItems(n int) {
if n < 4 {
for i := 0; i < n; i++ {
for range n {
emit.Opcodes(c.prog.BinWriter, opcode.DROP)
}
return
Expand Down Expand Up @@ -1930,7 +1930,7 @@ func (c *codegen) convertBuiltin(expr *ast.CallExpr) {
opcode.INC) // x y cnt+1
emit.Jmp(c.prog.BinWriter, opcode.JMPL, start)
c.setLabel(after)
for i := 0; i < 4; i++ { // leave x on stack
for range 4 { // leave x on stack
emit.Opcodes(c.prog.BinWriter, opcode.DROP)
}
} else {
Expand Down Expand Up @@ -2012,7 +2012,7 @@ func (c *codegen) emitConvert(typ stackitem.Type) {
func (c *codegen) convertByteArray(elems []ast.Expr) {
buf := make([]byte, len(elems))
varIndices := []int{}
for i := 0; i < len(elems); i++ {
for i := range elems {
t := c.typeAndValueOf(elems[i])
if t.Value != nil {
val, _ := constant.Int64Val(t.Value)
Expand Down Expand Up @@ -2508,7 +2508,7 @@ func removeNOPs(b []byte, nopOffsets []int, sequencePoints map[string][]DebugSeq
// 2. Convert instructions.
copyOffset := 0
l := len(nopOffsets)
for i := 0; i < l; i++ {
for i := range l {
start := nopOffsets[i]
end := len(b)
if i != l-1 {
Expand Down
8 changes: 4 additions & 4 deletions pkg/compiler/global_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -883,11 +883,11 @@ func TestMultipleFuncSameName(t *testing.T) {
func TestConstDontUseSlots(t *testing.T) {
const count = 256
buf := bytes.NewBufferString("package foo\n")
for i := 0; i < count; i++ {
for i := range count {
buf.WriteString(fmt.Sprintf("const n%d = 1\n", i))
}
buf.WriteString("func Main() int { sum := 0\n")
for i := 0; i < count; i++ {
for i := range count {
buf.WriteString(fmt.Sprintf("sum += n%d\n", i))
}
buf.WriteString("return sum }")
Expand All @@ -899,11 +899,11 @@ func TestConstDontUseSlots(t *testing.T) {
func TestUnderscoreVarsDontUseSlots(t *testing.T) {
const count = 128
buf := bytes.NewBufferString("package foo\n")
for i := 0; i < count; i++ {
for i := range count {
buf.WriteString(fmt.Sprintf("var _, n%d = 1, 1\n", i))
}
buf.WriteString("func Main() int { sum := 0\n")
for i := 0; i < count; i++ {
for i := range count {
buf.WriteString(fmt.Sprintf("sum += n%d\n", i))
}
buf.WriteString("return sum }")
Expand Down
2 changes: 1 addition & 1 deletion pkg/compiler/inline.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (c *codegen) inlineCall(f *funcScope, n *ast.CallExpr) {
ast.Walk(c, f.decl.Body)
c.setLabel(c.inlineContext[offSz].returnLabel)
if c.scope.voidCalls[n] {
for i := 0; i < f.decl.Type.Results.NumFields(); i++ {
for range f.decl.Type.Results.NumFields() {
emit.Opcodes(c.prog.BinWriter, opcode.DROP)
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/compiler/limit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestManyVariables(t *testing.T) {
const count = 155

buf := bytes.NewBufferString("package main\n")
for i := 0; i < count; i++ {
for i := range count {
buf.WriteString(fmt.Sprintf("var a%d = %d\n", i, i))
}
buf.WriteString("func Main() int {\nreturn 7\n}\n")
Expand Down
2 changes: 1 addition & 1 deletion pkg/compiler/native_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ func runNativeTestCase(t *testing.T, b *nef.File, di *compiler.DebugInfo, ctr in
if t.CallFlag != md.RequiredFlags {
return fmt.Errorf("wrong flags %v", t.CallFlag)
}
for i := 0; i < int(t.ParamCount); i++ {
for range t.ParamCount {
_ = v.Estack().Pop()
}
if v.Estack().Len() != 0 {
Expand Down
4 changes: 2 additions & 2 deletions pkg/compiler/syscall_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func runSyscallTestCase(t *testing.T, ic *interop.Context, realName string,
if ic.VM.Estack().Len() < f.ParamCount {
return errors.New("not enough parameters")
}
for i := 0; i < f.ParamCount; i++ {
for range f.ParamCount {
ic.VM.Estack().Pop()
}
if !tc.isVoid {
Expand Down Expand Up @@ -385,7 +385,7 @@ func TestInteropTypesComparison(t *testing.T) {
typeCheck := func(t *testing.T, typeName string, typeLen int) {
t.Run(typeName, func(t *testing.T) {
var ha, hb string
for i := 0; i < typeLen; i++ {
for i := range typeLen {
if i == typeLen-1 {
ha += "2"
hb += "3"
Expand Down
6 changes: 3 additions & 3 deletions pkg/consensus/consensus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ func TestService_GetVerified(t *testing.T) {
srv := newTestService(t)
srv.dbft.Start(0)
var txs []*transaction.Transaction
for i := 0; i < 4; i++ {
for i := range 4 {
tx := transaction.New([]byte{byte(opcode.PUSH1)}, 100000)
tx.Nonce = 123 + uint32(i)
tx.ValidUntilBlock = 1
Expand All @@ -208,7 +208,7 @@ func TestService_GetVerified(t *testing.T) {
hashes := []util.Uint256{txs[0].Hash(), txs[1].Hash(), txs[2].Hash()}

// Everyone sends a message.
for i := 0; i < 4; i++ {
for i := range 4 {
p := new(Payload)
// One PrepareRequest and three ChangeViews.
if i == 1 {
Expand Down Expand Up @@ -578,7 +578,7 @@ func addSender(t *testing.T, txs ...*transaction.Transaction) {
func signTx(t *testing.T, bc Ledger, txs ...*transaction.Transaction) {
validators := make([]*keys.PublicKey, 4)
privNetKeys := make([]*keys.PrivateKey, 4)
for i := 0; i < 4; i++ {
for i := range 4 {
privNetKeys[i] = testchain.PrivateKey(i)
validators[i] = privNetKeys[i].PublicKey()
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/consensus/payload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ func randomPrepareRequest(t *testing.T) *prepareRequest {
transactionHashes: make([]util.Uint256, txCount),
}

for i := 0; i < txCount; i++ {
for i := range txCount {
req.transactionHashes[i] = random.Uint256()
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/consensus/recovery_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func testRecoveryMessageSetters(t *testing.T, enableStateRoot bool) {
srv := newTestServiceWithState(t, enableStateRoot)
privs := make([]*privateKey, testchain.Size())
pubs := make([]dbft.PublicKey, testchain.Size())
for i := 0; i < testchain.Size(); i++ {
for i := range testchain.Size() {
privs[i], pubs[i] = getTestValidator(i)
}

Expand Down
14 changes: 7 additions & 7 deletions pkg/core/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func BenchmarkBlockchain_VerifyWitness(t *testing.B) {
tx := e.NewTx(t, []neotest.Signer{acc}, e.NativeHash(t, nativenames.Gas), "transfer", acc.ScriptHash(), acc.Script(), 1, nil)

t.ResetTimer()
for n := 0; n < t.N; n++ {
for range t.N {
_, err := bc.VerifyWitness(tx.Signers[0].Account, tx, &tx.Scripts[0], 100000000)
require.NoError(t, err)
}
Expand Down Expand Up @@ -92,9 +92,9 @@ func benchmarkForEachNEP17Transfer(t *testing.B, ps storage.Store, startFromBloc
acc := random.Uint160()
from := e.Validator.ScriptHash()

for j := 0; j < chainHeight; j++ {
for range chainHeight {
b := smartcontract.NewBuilder()
for i := 0; i < transfersPerBlock; i++ {
for range transfersPerBlock {
b.InvokeWithAssert(gasHash, "transfer", from, acc, 1, nil)
}
script, err := b.Script()
Expand All @@ -119,7 +119,7 @@ func benchmarkForEachNEP17Transfer(t *testing.B, ps storage.Store, startFromBloc
t.ResetTimer()
t.ReportAllocs()
t.StartTimer()
for i := 0; i < t.N; i++ {
for range t.N {
require.NoError(t, bc.ForEachNEP17Transfer(acc, newestTimestamp, func(t *state.NEP17Transfer) (bool, error) {
if t.Timestamp < oldestTimestamp {
// iterating from newest to oldest, already have reached the needed height
Expand Down Expand Up @@ -165,7 +165,7 @@ func benchmarkGasPerVote(t *testing.B, ps storage.Store, nRewardRecords int, rew
voters := make([]*wallet.Account, sz)
candidates := make(keys.PublicKeys, sz)
txs := make([]*transaction.Transaction, 0, len(voters)*3)
for i := 0; i < sz; i++ {
for i := range sz {
priv, err := keys.NewPrivateKey()
require.NoError(t, err)
candidates[i] = priv.PublicKey()
Expand All @@ -186,7 +186,7 @@ func benchmarkGasPerVote(t *testing.B, ps storage.Store, nRewardRecords int, rew
e.CheckHalt(t, tx.Hash())
}
voteTxs := make([]*transaction.Transaction, 0, sz)
for i := 0; i < sz; i++ {
for i := range sz {
priv := voters[i].PrivateKey()
h := priv.GetScriptHash()
voteTx := e.NewTx(t, []neotest.Signer{neotest.NewSingleSigner(voters[i])}, neoHash, "vote", h, candidates[i].Bytes())
Expand All @@ -211,7 +211,7 @@ func benchmarkGasPerVote(t *testing.B, ps storage.Store, nRewardRecords int, rew
t.ResetTimer()
t.ReportAllocs()
t.StartTimer()
for i := 0; i < t.N; i++ {
for range t.N {
_, err := bc.CalculateClaimable(to, end)
require.NoError(t, err)
}
Expand Down
6 changes: 3 additions & 3 deletions pkg/core/block/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func NewTrimmedFromReader(stateRootEnabled bool, br *io.BinReader) (*Block, erro
}
if lenHashes > 0 {
block.Transactions = make([]*transaction.Transaction, lenHashes)
for i := 0; i < int(lenHashes); i++ {
for i := range lenHashes {
var hash util.Uint256
hash.DecodeBinary(br)
block.Transactions[i] = transaction.NewTrimmedTX(hash)
Expand Down Expand Up @@ -124,7 +124,7 @@ func (b *Block) DecodeBinary(br *io.BinReader) {
return
}
txes := make([]*transaction.Transaction, contentsCount)
for i := 0; i < int(contentsCount); i++ {
for i := range txes {
tx := &transaction.Transaction{}
tx.DecodeBinary(br)
txes[i] = tx
Expand All @@ -140,7 +140,7 @@ func (b *Block) DecodeBinary(br *io.BinReader) {
func (b *Block) EncodeBinary(bw *io.BinWriter) {
b.Header.EncodeBinary(bw)
bw.WriteVarUint(uint64(len(b.Transactions)))
for i := 0; i < len(b.Transactions); i++ {
for i := range b.Transactions {
b.Transactions[i].EncodeBinary(bw)
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/core/block/block_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestTrimmedBlock(t *testing.T) {

assert.Equal(t, block.Script, trimmedBlock.Script)
assert.Equal(t, len(block.Transactions), len(trimmedBlock.Transactions))
for i := 0; i < len(block.Transactions); i++ {
for i := range block.Transactions {
assert.Equal(t, block.Transactions[i].Hash(), trimmedBlock.Transactions[i].Hash())
assert.True(t, trimmedBlock.Transactions[i].Trimmed)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/core/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -1203,7 +1203,7 @@ func (bc *Blockchain) resetTransfers(cache *dao.Simple, height uint32) error {
oldBatchSize = v[0]
newBatchSize byte
)
for i := byte(0); i < v[0]; i++ { // From oldest to newest transfer of the batch.
for range v[0] { // From oldest to newest transfer of the batch.
var t *state.NEP17Transfer
if k[0] == byte(storage.STNEP11Transfers) {
tr := new(state.NEP11Transfer)
Expand Down
Loading

0 comments on commit 1b83dc2

Please sign in to comment.