diff --git a/cmd/cue/cmd/custom.go b/cmd/cue/cmd/custom.go index 0474f6e9d..1d06cfa4a 100644 --- a/cmd/cue/cmd/custom.go +++ b/cmd/cue/cmd/custom.go @@ -49,8 +49,8 @@ func lookupString(obj cue.Value, key, def string) string { // splitLine splits the first line and the rest of the string. func splitLine(s string) (line, tail string) { line = s - if p := strings.IndexByte(s, '\n'); p >= 0 { - line, tail = strings.TrimSpace(s[:p]), strings.TrimSpace(s[p+1:]) + if before, after, ok := strings.Cut(s, "\n"); ok { + line, tail = strings.TrimSpace(before), strings.TrimSpace(after) } return } diff --git a/cue/format/printer.go b/cue/format/printer.go index 68e5b7c6b..f2ca7e026 100644 --- a/cue/format/printer.go +++ b/cue/format/printer.go @@ -401,7 +401,7 @@ func (p *printer) writeString(s string, isLit bool) { } func (p *printer) writeByte(ch byte, n int) { - for i := 0; i < n; i++ { + for range n { p.output = append(p.output, ch) } @@ -412,7 +412,7 @@ func (p *printer) writeByte(ch byte, n int) { p.pos.Column = 1 n := p.cfg.Indent + p.indent // include base indentation - for i := 0; i < n; i++ { + for range n { p.output = append(p.output, '\t') } diff --git a/cue/literal/string.go b/cue/literal/string.go index 342b91f32..72ceb56d8 100644 --- a/cue/literal/string.go +++ b/cue/literal/string.go @@ -405,7 +405,7 @@ func unquoteChar(s string, info QuoteInfo) (value rune, multibyte bool, tail str err = errSyntax return } - for j := 0; j < 2; j++ { // one digit already; two more + for j := range 2 { // one digit already; two more x := rune(s[j]) - '0' if x < 0 || x > 7 { err = errSyntax diff --git a/cue/load/loader_test.go b/cue/load/loader_test.go index dffff0bdf..450cd3c5e 100644 --- a/cue/load/loader_test.go +++ b/cue/load/loader_test.go @@ -855,7 +855,7 @@ func TestLoadInstancesConcurrent(t *testing.T) { func race(t *testing.T, f func() error) { var wg sync.WaitGroup - for i := 0; i < 2; i++ { + for range 2 { wg.Add(1) go func() { if err := f(); err != nil { diff --git a/cue/load/search.go b/cue/load/search.go index aa370073a..5782fab16 100644 --- a/cue/load/search.go +++ b/cue/load/search.go @@ -147,8 +147,8 @@ func (l *loader) matchPackagesInFS(pattern, pkgName string) *match { // // TODO this logic entirely ignores the pattern that's // after the "...". See cuelang.org/issue/3212 - i := strings.Index(pattern, "...") - dir, _ := path.Split(pattern[:i]) + before, _, _ := strings.Cut(pattern, "...") + dir, _ := path.Split(before) root := l.abs(dir) diff --git a/encoding/jsonschema/decode.go b/encoding/jsonschema/decode.go index 7c671017c..62473dbd0 100644 --- a/encoding/jsonschema/decode.go +++ b/encoding/jsonschema/decode.go @@ -855,7 +855,7 @@ func (s0 *state) schemaState(n cue.Value, types cue.Kind, init func(*state)) (ex } // do multiple passes over the constraints to ensure they are done in order. - for pass := 0; pass < numPhases; pass++ { + for pass := range numPhases { s.processMap(n, func(key string, value cue.Value) { if pass == 0 && key == "$ref" { // Before 2019-19, keywords alongside $ref are ignored so keep diff --git a/internal/anyunique/unique_test.go b/internal/anyunique/unique_test.go index d2bb665af..d08a24ae5 100644 --- a/internal/anyunique/unique_test.go +++ b/internal/anyunique/unique_test.go @@ -284,7 +284,7 @@ func TestStore_Make_RepeatedCalls(t *testing.T) { // Make the same value many times var values []anyunique.Handle[string] - for i := 0; i < 100; i++ { + for range 100 { values = append(values, s.Make("repeated")) } @@ -352,14 +352,14 @@ func TestStore_Make_StressTest(t *testing.T) { n := 10000 uniqueMap := make(map[int]anyunique.Handle[int]) - for i := 0; i < n; i++ { + for i := range n { u := s.Make(i) uniqueMap[i] = u qt.Assert(t, qt.Equals(u.Value(), i)) } // Verify all values are stored correctly and re-making gives equal results - for i := 0; i < n; i++ { + for i := range n { u := s.Make(i) qt.Assert(t, qt.Equals(u, uniqueMap[i])) } @@ -497,7 +497,7 @@ func TestStore_Make_AlternatingPatterns(t *testing.T) { s := anyunique.New[string](stringHasher{}) // Alternate between two values many times - for i := 0; i < 100; i++ { + for range 100 { u1 := s.Make("a") u2 := s.Make("b") u3 := s.Make("a") diff --git a/internal/astinternal/debug.go b/internal/astinternal/debug.go index f2e4a21ce..da43916f9 100644 --- a/internal/astinternal/debug.go +++ b/internal/astinternal/debug.go @@ -447,33 +447,34 @@ func DebugStr(x interface{}) (out string) { return out case *ast.Field: - out := DebugStr(v.Label) + var out strings.Builder + out.WriteString(DebugStr(v.Label)) if v.Alias != nil { - out += "~" + out.WriteString("~") if v.Alias.Label != nil { // Dual form - out += "(" - out += DebugStr(v.Alias.Label) - out += "," - out += DebugStr(v.Alias.Field) - out += ")" + out.WriteString("(") + out.WriteString(DebugStr(v.Alias.Label)) + out.WriteString(",") + out.WriteString(DebugStr(v.Alias.Field)) + out.WriteString(")") } else { // Simple form - out += DebugStr(v.Alias.Field) + out.WriteString(DebugStr(v.Alias.Field)) } } if t := v.Constraint; t != token.ILLEGAL { - out += t.String() + out.WriteString(t.String()) } if v.Value != nil { - out += ": " - out += DebugStr(v.Value) + out.WriteString(": ") + out.WriteString(DebugStr(v.Value)) for _, a := range v.Attrs { - out += " " - out += DebugStr(a) + out.WriteString(" ") + out.WriteString(DebugStr(a)) } } - return out + return out.String() case *ast.Attribute: return v.Text @@ -578,12 +579,12 @@ func DebugStr(x interface{}) (out string) { if len(v) == 0 { return "" } - out := "" + var out strings.Builder for _, c := range v { - out += DebugStr(c) - out += " " + out.WriteString(DebugStr(c)) + out.WriteString(" ") } - return out + return out.String() case []ast.Expr: if len(v) == 0 { diff --git a/internal/attrs.go b/internal/attrs.go index b3d1918ea..5e082d4f6 100644 --- a/internal/attrs.go +++ b/internal/attrs.go @@ -273,7 +273,7 @@ func scanAttributeTokens(s *scanner.Scanner, startPos token.Pos, close uint64) ( func tokenMaskStr(m uint64) string { var buf strings.Builder - for t := token.Token(0); t < 64; t++ { + for t := range token.Token(64) { if (m & (1 << t)) != 0 { if buf.Len() > 0 { buf.WriteByte('|') diff --git a/internal/core/adt/composite.go b/internal/core/adt/composite.go index faad9ae94..202633794 100644 --- a/internal/core/adt/composite.go +++ b/internal/core/adt/composite.go @@ -126,7 +126,7 @@ func (e *Environment) DerefVertex(ctx *OpContext) *Vertex { } func (e *Environment) up(ctx *OpContext, count int32) *Environment { - for i := int32(0); i < count; i++ { + for range count { e = e.Up ctx.Assertf(ctx.Pos(), e.DerefVertex(ctx) != nil, "Environment.up encountered a nil vertex") } diff --git a/internal/core/adt/debug.go b/internal/core/adt/debug.go index 93fe9cb38..955b3c4d1 100644 --- a/internal/core/adt/debug.go +++ b/internal/core/adt/debug.go @@ -491,7 +491,7 @@ func indentOnNewline(w io.Writer, level int) { } func indent(w io.Writer, level int) { - for i := 0; i < level; i++ { + for range level { io.WriteString(w, " ") } } diff --git a/internal/core/adt/disjunct2.go b/internal/core/adt/disjunct2.go index ae5d16a94..86cd83cc8 100644 --- a/internal/core/adt/disjunct2.go +++ b/internal/core/adt/disjunct2.go @@ -288,7 +288,7 @@ func (n *nodeContext) processDisjunctions() *Bottom { // Slow path for processing all disjunctions. Do not use `range` in case // evaluation adds more disjunctions. - for i := 0; i < len(a); i++ { + for i := range a { d := &a[i] n.nextDisjunction(i, len(a), d.holeID) diff --git a/internal/core/adt/eval_test.go b/internal/core/adt/eval_test.go index 041a39f46..0f2bdc822 100644 --- a/internal/core/adt/eval_test.go +++ b/internal/core/adt/eval_test.go @@ -261,7 +261,7 @@ func BenchmarkUnifyAPI(b *testing.B) { b.StopTimer() ctx := cuecontext.New() v := ctx.CompileString("") - for j := 0; j < 500; j++ { + for j := range 500 { if j == 400 { b.StartTimer() } diff --git a/internal/core/export/toposort.go b/internal/core/export/toposort.go index e3d365862..1660e0ea4 100644 --- a/internal/core/export/toposort.go +++ b/internal/core/export/toposort.go @@ -53,7 +53,7 @@ func extractFeatures(in []adt.StructInfo) (a [][]adt.Feature) { if len(sorted) > 0 { occurrences := 1 + s.Repeats // Add this front (1 + Repeats) times to give it proper weight - for i := 0; i < occurrences; i++ { + for range occurrences { a = append(a, sorted) } } diff --git a/internal/golangorgx/gopls/lsprpc/autostart_posix.go b/internal/golangorgx/gopls/lsprpc/autostart_posix.go index 57ccba958..255889c5e 100644 --- a/internal/golangorgx/gopls/lsprpc/autostart_posix.go +++ b/internal/golangorgx/gopls/lsprpc/autostart_posix.go @@ -3,7 +3,6 @@ // license that can be found in the LICENSE file. //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris -// +build darwin dragonfly freebsd linux netbsd openbsd solaris package lsprpc diff --git a/internal/golangorgx/gopls/lsprpc/dialer.go b/internal/golangorgx/gopls/lsprpc/dialer.go index 977242f0b..0a7c862d1 100644 --- a/internal/golangorgx/gopls/lsprpc/dialer.go +++ b/internal/golangorgx/gopls/lsprpc/dialer.go @@ -97,7 +97,7 @@ func (d *autoDialer) dialNet(ctx context.Context) (net.Conn, error) { const retries = 5 // It can take some time for the newly started server to bind to our address, // so we retry for a bit. - for retry := 0; retry < retries; retry++ { + for retry := range retries { startDial := time.Now() netConn, err = net.DialTimeout(d.network, d.addr, dialTimeout) if err == nil { diff --git a/internal/golangorgx/gopls/protocol/semantic.go b/internal/golangorgx/gopls/protocol/semantic.go index 65253d032..c393e32f7 100644 --- a/internal/golangorgx/gopls/protocol/semantic.go +++ b/internal/golangorgx/gopls/protocol/semantic.go @@ -33,7 +33,7 @@ func SemType(n int) string { func SemMods(n int) []string { tokMods := SemanticModifiers() mods := []string{} - for i := 0; i < len(tokMods); i++ { + for i := range tokMods { if (n & (1 << uint(i))) != 0 { mods = append(mods, tokMods[i]) } diff --git a/internal/golangorgx/gopls/protocol/semtok/semtok.go b/internal/golangorgx/gopls/protocol/semtok/semtok.go index e69ec825f..026627bb7 100644 --- a/internal/golangorgx/gopls/protocol/semtok/semtok.go +++ b/internal/golangorgx/gopls/protocol/semtok/semtok.go @@ -65,7 +65,7 @@ func Encode( x := make([]uint32, 5*len(tokens)) var j int var last Token - for i := 0; i < len(tokens); i++ { + for i := range tokens { item := tokens[i] typ, ok := typeMap[item.Type] if !ok { diff --git a/internal/golangorgx/gopls/settings/settings.go b/internal/golangorgx/gopls/settings/settings.go index 6650749a4..50752d757 100644 --- a/internal/golangorgx/gopls/settings/settings.go +++ b/internal/golangorgx/gopls/settings/settings.go @@ -7,6 +7,7 @@ package settings import ( "context" "fmt" + "maps" "path/filepath" "regexp" "runtime" @@ -709,9 +710,7 @@ func (o *Options) Clone() *Options { // and UserOptions can be modified. copyStringMap := func(src map[string]bool) map[string]bool { dst := make(map[string]bool) - for k, v := range src { - dst[k] = v - } + maps.Copy(dst, src) return dst } result.Analyses = copyStringMap(o.Analyses) @@ -729,9 +728,7 @@ func (o *Options) Clone() *Options { copyAnalyzerMap := func(src map[string]*Analyzer) map[string]*Analyzer { dst := make(map[string]*Analyzer) - for k, v := range src { - dst[k] = v - } + maps.Copy(dst, src) return dst } result.DefaultAnalyzers = copyAnalyzerMap(o.DefaultAnalyzers) @@ -921,9 +918,7 @@ func (o *Options) set(name string, value interface{}, seen map[string]struct{}) if o.Codelenses == nil { o.Codelenses = make(map[string]bool) } - for lens, enabled := range lensOverrides { - o.Codelenses[lens] = enabled - } + maps.Copy(o.Codelenses, lensOverrides) } case "staticcheck": diff --git a/internal/golangorgx/gopls/test/integration/expectation.go b/internal/golangorgx/gopls/test/integration/expectation.go index 1e01a2a59..1743fcbc9 100644 --- a/internal/golangorgx/gopls/test/integration/expectation.go +++ b/internal/golangorgx/gopls/test/integration/expectation.go @@ -6,8 +6,9 @@ package integration import ( "fmt" + "maps" "regexp" - "sort" + "slices" "strings" "cuelang.org/go/internal/golangorgx/gopls/protocol" @@ -200,9 +201,7 @@ func ReadDiagnostics(fileName string, into *protocol.PublishDiagnosticsParams) E func ReadAllDiagnostics(into *map[string]*protocol.PublishDiagnosticsParams) Expectation { check := func(s State) Verdict { allDiags := make(map[string]*protocol.PublishDiagnosticsParams) - for name, diags := range s.diagnostics { - allDiags[name] = diags - } + maps.Copy(allDiags, s.diagnostics) *into = allDiags return Met } @@ -311,9 +310,7 @@ func (e *Env) DoneDiagnosingChanges() Expectation { } // Sort for stability. - sort.Slice(expected, func(i, j int) bool { - return expected[i] < expected[j] - }) + slices.Sort(expected) var all []Expectation for _, source := range expected { diff --git a/internal/golangorgx/gopls/test/integration/fake/editor.go b/internal/golangorgx/gopls/test/integration/fake/editor.go index 337d2d7ea..513960897 100644 --- a/internal/golangorgx/gopls/test/integration/fake/editor.go +++ b/internal/golangorgx/gopls/test/integration/fake/editor.go @@ -228,9 +228,7 @@ func (e *Editor) Client() *Client { // makeSettings builds the settings map for use in LSP settings RPCs. func makeSettings(sandbox *Sandbox, config EditorConfig, scopeURI *protocol.URI) map[string]any { env := make(map[string]string) - for k, v := range config.Env { - env[k] = v - } + maps.Copy(env, config.Env) for k, v := range env { v = strings.ReplaceAll(v, "$SANDBOX_WORKDIR", sandbox.Workdir.RootURI().Path()) env[k] = v diff --git a/internal/golangorgx/gopls/test/integration/options.go b/internal/golangorgx/gopls/test/integration/options.go index 15fdba943..88c6282d8 100644 --- a/internal/golangorgx/gopls/test/integration/options.go +++ b/internal/golangorgx/gopls/test/integration/options.go @@ -5,6 +5,8 @@ package integration import ( + "maps" + "cuelang.org/go/internal/golangorgx/gopls/protocol" "cuelang.org/go/internal/golangorgx/gopls/test/integration/fake" "cuelang.org/go/internal/lsp/cache" @@ -92,9 +94,7 @@ func (s Settings) set(opts *runConfig) { if opts.editor.Settings == nil { opts.editor.Settings = make(map[string]interface{}) } - for k, v := range s { - opts.editor.Settings[k] = v - } + maps.Copy(opts.editor.Settings, s) } // WorkspaceFolders configures the workdir-relative workspace folders to send @@ -156,9 +156,7 @@ func (e EnvVars) set(opts *runConfig) { if opts.editor.Env == nil { opts.editor.Env = make(map[string]string) } - for k, v := range e { - opts.editor.Env[k] = v - } + maps.Copy(opts.editor.Env, e) } // MessageResponder configures the editor to respond to diff --git a/internal/golangorgx/tools/diff/lcs/old.go b/internal/golangorgx/tools/diff/lcs/old.go index a14ae9119..e3d29cfeb 100644 --- a/internal/golangorgx/tools/diff/lcs/old.go +++ b/internal/golangorgx/tools/diff/lcs/old.go @@ -376,10 +376,7 @@ func (e *editGraph) twoDone(df, db int) (int, bool) { if (df+db+e.delta)%2 != 0 { return 0, false // diagonals cannot overlap } - kmin := -db + e.delta - if -df > kmin { - kmin = -df - } + kmin := max(-df, -db+e.delta) kmax := db + e.delta if df < kmax { kmax = df diff --git a/internal/golangorgx/tools/diff/lcs/sequence.go b/internal/golangorgx/tools/diff/lcs/sequence.go index 2d72d2630..811bb216e 100644 --- a/internal/golangorgx/tools/diff/lcs/sequence.go +++ b/internal/golangorgx/tools/diff/lcs/sequence.go @@ -103,11 +103,3 @@ func commonSuffixLenString(a, b string) int { } return i } - -func min(x, y int) int { - if x < y { - return x - } else { - return y - } -} diff --git a/internal/golangorgx/tools/diff/ndiff.go b/internal/golangorgx/tools/diff/ndiff.go index 7c8fb29e6..bbdde2062 100644 --- a/internal/golangorgx/tools/diff/ndiff.go +++ b/internal/golangorgx/tools/diff/ndiff.go @@ -72,7 +72,7 @@ func diffRunes(before, after []rune) []Edit { func runes(bytes []byte) []rune { n := utf8.RuneCount(bytes) runes := make([]rune, n) - for i := 0; i < n; i++ { + for i := range n { r, sz := utf8.DecodeRune(bytes) bytes = bytes[sz:] runes[i] = r diff --git a/internal/golangorgx/tools/event/export/ocagent/metrics.go b/internal/golangorgx/tools/event/export/ocagent/metrics.go index 521c6470e..7b29a5541 100644 --- a/internal/golangorgx/tools/event/export/ocagent/metrics.go +++ b/internal/golangorgx/tools/event/export/ocagent/metrics.go @@ -104,7 +104,7 @@ func dataToTimeseries(data metric.Data, start time.Time) []*wire.TimeSeries { startTimestamp := convertTimestamp(start) timeseries := make([]*wire.TimeSeries, 0, numRows) - for i := 0; i < numRows; i++ { + for i := range numRows { timeseries = append(timeseries, &wire.TimeSeries{ StartTimestamp: &startTimestamp, // TODO: labels? @@ -175,7 +175,7 @@ func dataToPoints(data metric.Data, i int) []*wire.Point { // supplied counts, count, and sum. func distributionToPoints(counts []int64, count int64, sum float64, bucketBounds []float64, end time.Time) []*wire.Point { buckets := make([]*wire.Bucket, len(counts)) - for i := 0; i < len(counts); i++ { + for i := range counts { buckets[i] = &wire.Bucket{ Count: counts[i], } diff --git a/internal/mod/mvs/mvs_test.go b/internal/mod/mvs/mvs_test.go index f970847b5..e34adefdb 100644 --- a/internal/mod/mvs/mvs_test.go +++ b/internal/mod/mvs/mvs_test.go @@ -481,12 +481,12 @@ func Test(t *testing.T) { if strings.HasPrefix(line, "#") || line == "" { continue } - i := strings.Index(line, ":") - if i < 0 { + before, after, ok := strings.Cut(line, ":") + if !ok { t.Fatalf("missing colon: %q", line) } - key := strings.TrimSpace(line[:i]) - val := strings.TrimSpace(line[i+1:]) + key := strings.TrimSpace(before) + val := strings.TrimSpace(after) if key == "" { t.Fatalf("missing key: %q", line) } diff --git a/mod/modconfig/modconfig_test.go b/mod/modconfig/modconfig_test.go index 99e94151d..e4e579318 100644 --- a/mod/modconfig/modconfig_test.go +++ b/mod/modconfig/modconfig_test.go @@ -194,13 +194,13 @@ func TestConcurrentTokenRefresh(t *testing.T) { for i := range registries { reg := ®istries[i] reg.mod = fmt.Sprintf("foo.mod%02d", i) - fsys, err := txtar.FS(txtar.Parse([]byte(fmt.Sprintf(` + fsys, err := txtar.FS(txtar.Parse(fmt.Appendf(nil, ` -- %s_v0.0.1/cue.mod/module.cue -- module: "%s@v0" language: version: "v0.8.0" -- %s_v0.0.1/bar/bar.cue -- package bar -`, reg.mod, reg.mod, reg.mod)))) +`, reg.mod, reg.mod, reg.mod))) qt.Assert(t, qt.IsNil(err)) mux := http.NewServeMux() r := ocimem.New() diff --git a/mod/modzip/zip_test.go b/mod/modzip/zip_test.go index 219360cba..c00dd585f 100644 --- a/mod/modzip/zip_test.go +++ b/mod/modzip/zip_test.go @@ -58,11 +58,11 @@ func readTest(file string) (testParams, error) { if line == "" || line[0] == '#' { continue } - eq := strings.IndexByte(line, '=') - if eq < 0 { + before, after, ok := strings.Cut(line, "=") + if !ok { return testParams{}, fmt.Errorf("%s:%d: missing = separator", file, n) } - key, value := strings.TrimSpace(line[:eq]), strings.TrimSpace(line[eq+1:]) + key, value := strings.TrimSpace(before), strings.TrimSpace(after) if strings.HasPrefix(value, "\"") { unq, err := strconv.Unquote(value) if err != nil { diff --git a/pkg/path/path.go b/pkg/path/path.go index 247dd7b3f..a7cc3dd94 100644 --- a/pkg/path/path.go +++ b/pkg/path/path.go @@ -319,7 +319,7 @@ func Rel(basepath, targpath string, os OS) (string, error) { } buf := make([]byte, size) n := copy(buf, "..") - for i := 0; i < seps; i++ { + for range seps { buf[n] = x.Separator copy(buf[n+1:], "..") n += 3