diff --git a/Makefile b/Makefile index 1eb02576ea..5b088bfd9c 100644 --- a/Makefile +++ b/Makefile @@ -26,7 +26,7 @@ CONDITIONAL_WASM_TAG := -tags=opa_wasm endif override GO_TAGS := $(GO_TAGS) $(CONDITIONAL_WASM_TAG) -GOLANGCI_LINT_VERSION := v2.6.2 +GOLANGCI_LINT_VERSION := v2.9.0 YAML_LINT_VERSION := 0.29.0 YAML_LINT_FORMAT ?= auto diff --git a/cmd/build_test.go b/cmd/build_test.go index 56e8a9bdb0..077afddf1a 100644 --- a/cmd/build_test.go +++ b/cmd/build_test.go @@ -77,6 +77,7 @@ func TestBuildProducesBundle(t *testing.T) { } func TestBuildRespectsCapabilities(t *testing.T) { + //nolint:prealloc // test slice is extended dynamically, initial values are clearer as slice literal tests := []struct { note string caps string @@ -3276,7 +3277,7 @@ Warning: .manifest file found in %q but -b flag not specified. Manifest will be params.bundleMode = tc.bundleMode params.stderr = &stderr - var args []string + args := make([]string, 0, len(tc.buildArgs)) for _, arg := range tc.buildArgs { args = append(args, path.Join(root, arg)) } diff --git a/cmd/check_test.go b/cmd/check_test.go index 998ac09faf..8bcf87863f 100644 --- a/cmd/check_test.go +++ b/cmd/check_test.go @@ -20,6 +20,7 @@ import ( ) func TestCheckRespectsCapabilities(t *testing.T) { + //nolint:prealloc // test slice is extended dynamically, initial values are clearer as slice literal tests := []struct { note string caps string diff --git a/cmd/eval_test.go b/cmd/eval_test.go index 063075f06a..0d5f162cb9 100755 --- a/cmd/eval_test.go +++ b/cmd/eval_test.go @@ -1185,10 +1185,10 @@ func TestEvalWithStrictBuiltinErrors(t *testing.T) { func assertResultSet(t *testing.T, rs rego.ResultSet, expected string) { t.Helper() - result := []any{} + result := make([]any, 0, len(rs)) for i := range rs { - values := []any{} + values := make([]any, 0, len(rs[i].Expressions)) for j := range rs[i].Expressions { values = append(values, rs[i].Expressions[j].Value) } diff --git a/cmd/parse_test.go b/cmd/parse_test.go index acc59582a4..ce036565d5 100644 --- a/cmd/parse_test.go +++ b/cmd/parse_test.go @@ -1187,7 +1187,7 @@ func testParse(t *testing.T, files map[string]string, params *parseParams) (int, var tempDirUsed string test.WithTempFS(files, func(path string) { - var args []string + args := make([]string, 0, len(files)) for file := range files { args = append(args, filepath.Join(path, file)) } diff --git a/internal/bundle/inspect/inspect_test.go b/internal/bundle/inspect/inspect_test.go index 5e17cc382c..8efedf6ef1 100644 --- a/internal/bundle/inspect/inspect_test.go +++ b/internal/bundle/inspect/inspect_test.go @@ -62,7 +62,7 @@ func TestGenerateBundleInfoWithFileDir(t *testing.T) { t.Fatalf("expected namespaces %v, but got %v", expectedNamespaces, info.Namespaces) } - var builtinNames []string + builtinNames := make([]string, 0, len(info.Required.Builtins)) for _, bi := range info.Required.Builtins { builtinNames = append(builtinNames, bi.Name) } @@ -250,7 +250,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) { t.Fatalf("expected namespaces %v, but got %v", expectedNamespaces, info.Namespaces) } - expectedWasmModules := []map[string]any{} + expectedWasmModules := make([]map[string]any, 0, 2) expectedWasmModule1 := map[string]any{ "path": "/example/policy.wasm", "url": filepath.Join(bundleFile, "example", "policy.wasm"), diff --git a/internal/compiler/wasm/wasm.go b/internal/compiler/wasm/wasm.go index 92a117112a..e531a9b9b9 100644 --- a/internal/compiler/wasm/wasm.go +++ b/internal/compiler/wasm/wasm.go @@ -1285,6 +1285,7 @@ func (c *Compiler) compileScan(scan *ir.ScanStmt, result *[]instruction.Instruct } func (c *Compiler) compileScanBlock(scan *ir.ScanStmt) ([]instruction.Instruction, error) { + //nolint:prealloc // instruction list is known and fixed, clearer as slice literal instrs := []instruction.Instruction{ // Execute iterator. instruction.GetLocal{Index: c.local(scan.Source)}, @@ -1486,7 +1487,7 @@ func (c *Compiler) compileUpsert(local ir.Local, path []int, value ir.Operand, _ } func (c *Compiler) compileCallDynamicStmt(stmt *ir.CallDynamicStmt, result *[]instruction.Instruction) error { - instrs := []instruction.Instruction{} + instrs := make([]instruction.Instruction, 0, 3+3*len(stmt.Path)+len(stmt.Args)+10) larray := c.genLocal() lidx := c.genLocal() @@ -1559,7 +1560,7 @@ func (c *Compiler) compileCallStmt(stmt *ir.CallStmt, result *[]instruction.Inst func (c *Compiler) compileInternalCall(stmt *ir.CallStmt, index uint32, result *[]instruction.Instruction) error { - instrs := []instruction.Instruction{} + instrs := make([]instruction.Instruction, 0, len(stmt.Args)+4) // Prepare function args and call. for _, arg := range stmt.Args { diff --git a/internal/levenshtein/levenshtein.go b/internal/levenshtein/levenshtein.go index 63b93aa6da..217081a68d 100644 --- a/internal/levenshtein/levenshtein.go +++ b/internal/levenshtein/levenshtein.go @@ -16,7 +16,8 @@ func ClosestStrings(minDistance int, a string, candidates iter.Seq[string]) []st levDist := levenshtein.ComputeDistance(a, c) switch { case levDist < minDistance: - closestStrings = []string{c} + closestStrings = make([]string, 1, 2) + closestStrings[0] = c minDistance = levDist case levDist == minDistance: closestStrings = append(closestStrings, c) diff --git a/internal/pathwatcher/utils_test.go b/internal/pathwatcher/utils_test.go index 52d2294aea..ee05ab5aac 100644 --- a/internal/pathwatcher/utils_test.go +++ b/internal/pathwatcher/utils_test.go @@ -37,7 +37,7 @@ func TestWatchPaths(t *testing.T) { if err != nil { t.Fatalf("Unexpected error: %v", err) } - result := []string{} + result := make([]string, 0, len(paths)) for _, p := range paths { result = append(result, filepath.Clean(strings.TrimPrefix(p, rootDir))) } diff --git a/internal/planner/planner.go b/internal/planner/planner.go index 6ec686d571..445b5d7c2a 100644 --- a/internal/planner/planner.go +++ b/internal/planner/planner.go @@ -2070,7 +2070,7 @@ func (p *Planner) planRefDataExtent(virtual *ruletrie, base *baseptr, iter plani } } if anyKeyNonGround { - var rules []*ast.Rule + rules := make([]*ast.Rule, 0, len(virtual.Children())) for _, key := range virtual.Children() { // TODO(sr): skip functions rules = append(rules, virtual.Get(key).Rules()...) diff --git a/internal/presentation/presentation.go b/internal/presentation/presentation.go index 9f7397ee08..902be00dc0 100644 --- a/internal/presentation/presentation.go +++ b/internal/presentation/presentation.go @@ -544,7 +544,7 @@ func prettyProfile(w io.Writer, profile []profiler.ExprStats) error { tableProfile := generateTableProfile(w) for _, rs := range profile { - line := []string{} + line := make([]string, 0, 5) timeNs := time.Duration(rs.ExprTimeNs) * time.Nanosecond timeNsStr := timeNs.String() numEval := strconv.FormatInt(int64(rs.NumEval), 10) @@ -695,13 +695,13 @@ func populateTableMetrics(m metrics.Metrics, table *tablewriter.Table, prettyLim for varName, varValueInterface := range m.All() { val, ok := varValueInterface.(map[string]any) if !ok { - line := []string{} + line := make([]string, 0, 2) varValue := checkStrLimit(fmt.Sprintf("%v", varValueInterface), prettyLimit) line = append(line, varName, varValue) lines = append(lines, line) } else { for k, v := range val { - line := []string{} + line := make([]string, 0, 2) newVarName := fmt.Sprintf("%v_%v", varName, k) value := checkStrLimit(fmt.Sprintf("%v", v), prettyLimit) line = append(line, newVarName, value) @@ -718,9 +718,10 @@ func populateTableMetrics(m metrics.Metrics, table *tablewriter.Table, prettyLim } func populateTableAggregatedMetrics(ms map[string]any, table *tablewriter.Table, prettyLimit int) (int, error) { - lines := [][]string{} + lines := make([][]string, 0, len(ms)) for name, vals := range ms { - line := []string{name} + line := make([]string, 0, 1+len(statKeys)) + line = append(line, name) vs := vals.(map[string]any) for _, k := range statKeys { line = append(line, checkStrLimit(fmt.Sprintf("%v", vs[k]), prettyLimit)) diff --git a/internal/runtime/init/init_test.go b/internal/runtime/init/init_test.go index 19c1f5953e..667f7cccb4 100644 --- a/internal/runtime/init/init_test.go +++ b/internal/runtime/init/init_test.go @@ -432,7 +432,7 @@ func TestWalkPaths(t *testing.T) { test.WithTempFS(files, func(rootDir string) { - paths := []string{} + paths := make([]string, 0, 2) paths = append(paths, filepath.Join(rootDir, "bundle1"), filepath.Join(rootDir, "bundle2")) // bundle mode diff --git a/ir/encoding/encoding_test.go b/ir/encoding/encoding_test.go index b4c88d493c..e7f0061979 100644 --- a/ir/encoding/encoding_test.go +++ b/ir/encoding/encoding_test.go @@ -27,7 +27,7 @@ func TestRoundTrip(t *testing.T) { t.Fatal(err) } - modules := []*ast.Module{} + modules := make([]*ast.Module, 0, len(c.Modules)) for _, m := range c.Modules { modules = append(modules, m) diff --git a/v1/ast/compile.go b/v1/ast/compile.go index 71554e48f3..2ee66e2695 100644 --- a/v1/ast/compile.go +++ b/v1/ast/compile.go @@ -974,7 +974,7 @@ func (c *Compiler) PassesTypeCheck(body Body) bool { // PassesTypeCheckRules determines whether the given rules passes type checking func (c *Compiler) PassesTypeCheckRules(rules []*Rule) Errors { - elems := []util.T{} + elems := make([]util.T, 0, len(rules)) for _, rule := range rules { elems = append(elems, rule) diff --git a/v1/ast/compile_test.go b/v1/ast/compile_test.go index ec655e4fd5..4ccefec849 100644 --- a/v1/ast/compile_test.go +++ b/v1/ast/compile_test.go @@ -5615,7 +5615,7 @@ func TestRewriteLocalVarDeclarationErrors(t *testing.T) { sort.Strings(expectedErrors) - result := []string{} + result := make([]string, 0, len(c.Errors)) for i := range c.Errors { result = append(result, c.Errors[i].Message) @@ -11544,7 +11544,7 @@ foorule = true if { } func compilerErrsToStringSlice(errors []*Error) []string { - result := []string{} + result := make([]string, 0, len(errors)) for _, e := range errors { msg := strings.SplitN(e.Error(), ":", 3)[2] result = append(result, strings.TrimSpace(msg)) diff --git a/v1/ast/policy.go b/v1/ast/policy.go index 4ce31953f3..632b5aa6d5 100644 --- a/v1/ast/policy.go +++ b/v1/ast/policy.go @@ -989,7 +989,7 @@ func (head *Head) HasDynamicRef() bool { // Copy returns a deep copy of a. func (a Args) Copy() Args { - cpy := Args{} + cpy := make(Args, 0, len(a)) for _, t := range a { cpy = append(cpy, t.Copy()) } diff --git a/v1/ast/schema_test.go b/v1/ast/schema_test.go index 3955dfb517..8202488e21 100644 --- a/v1/ast/schema_test.go +++ b/v1/ast/schema_test.go @@ -361,7 +361,7 @@ func TestAllOfSchemas(t *testing.T) { func TestParseSchemaUntypedField(t *testing.T) { // Expected type is: object - staticProps := []*types.StaticProperty{} + staticProps := make([]*types.StaticProperty, 0, 1) staticProps = append(staticProps, &types.StaticProperty{Key: "foo", Value: types.A}) expectedType := types.NewObject(staticProps, nil) testParseSchema(t, untypedFieldObjectSchema, expectedType, nil) @@ -375,7 +375,7 @@ func TestParseSchemaNoChildren(t *testing.T) { func TestParseSchemaArrayNoItems(t *testing.T) { // Expected type is: object - staticProps := []*types.StaticProperty{} + staticProps := make([]*types.StaticProperty, 0, 1) staticProps = append(staticProps, &types.StaticProperty{Key: "b", Value: types.NewArray(nil, types.A)}) expectedType := types.NewObject(staticProps, nil) testParseSchema(t, arrayNoItemsSchema, expectedType, nil) @@ -383,7 +383,7 @@ func TestParseSchemaArrayNoItems(t *testing.T) { func TestParseSchemaBooleanField(t *testing.T) { // Expected type is: object - staticProps := []*types.StaticProperty{} + staticProps := make([]*types.StaticProperty, 0, 1) staticProps = append(staticProps, &types.StaticProperty{Key: "a", Value: types.B}) expectedType := types.NewObject(staticProps, nil) testParseSchema(t, booleanSchema, expectedType, nil) diff --git a/v1/ast/term_test.go b/v1/ast/term_test.go index f56c0074a5..ff93964749 100644 --- a/v1/ast/term_test.go +++ b/v1/ast/term_test.go @@ -755,7 +755,7 @@ func TestRefExtend(t *testing.T) { func TestRefConcat(t *testing.T) { a := MustParseRef("foo.bar.baz") - terms := []*Term{} + terms := make([]*Term, 0, 2) if !a.Concat(terms).Equal(a) { t.Fatal("Expected no change") } diff --git a/v1/bundle/sign_test.go b/v1/bundle/sign_test.go index cfad8cc9cd..93086c6e32 100644 --- a/v1/bundle/sign_test.go +++ b/v1/bundle/sign_test.go @@ -28,7 +28,7 @@ func TestGenerateSignedToken(t *testing.T) { {"/data.json", `{"x": {"y": true}, "a": {"b": {"z": true}}}`}, } - input := []FileInfo{} + input := make([]FileInfo, 0, len(files)) expDigests := make([]string, len(files)) expDigests[0] = "a005c38a509dc2d5a7407b9494efb2ad" @@ -77,7 +77,7 @@ func TestGenerateSignedTokenWithClaims(t *testing.T) { {"/data.json", `{"x": {"y": true}, "a": {"b": {"z": true}}}}`}, } - input := []FileInfo{} + input := make([]FileInfo, 0, len(files)) expDigests := make([]string, len(files)) expDigests[0] = "a005c38a509dc2d5a7407b9494efb2ad" @@ -148,7 +148,7 @@ func TestGeneratePayload(t *testing.T) { {"/.manifest", `{"revision": "quickbrownfaux"}`}, } - input := []FileInfo{} + input := make([]FileInfo, 0, 1) file := FileInfo{ Name: files[0][0], diff --git a/v1/bundle/store_test.go b/v1/bundle/store_test.go index 865530f4fe..51c101e0c8 100644 --- a/v1/bundle/store_test.go +++ b/v1/bundle/store_test.go @@ -3696,7 +3696,7 @@ func testWriteData(t *testing.T, tc testWriteModuleCase, legacy bool) { // if supplied, pre-parse the module files for _, b := range tc.bundles { - var parsedMods []ModuleFile + parsedMods := make([]ModuleFile, 0, len(b.Modules)) for _, mf := range b.Modules { parsedMods = append(parsedMods, ModuleFile{ Path: mf.Path, diff --git a/v1/compile/compile_test.go b/v1/compile/compile_test.go index 3474874d58..781fa97d98 100644 --- a/v1/compile/compile_test.go +++ b/v1/compile/compile_test.go @@ -3695,7 +3695,9 @@ type prettyBundle struct { } func (p prettyBundle) String() string { - buf := []string{fmt.Sprintf("%d module(s) (hiding data):", len(p.Modules)), ""} + buf := make([]string, 2, 2+len(p.Modules)*5) + buf[0] = fmt.Sprintf("%d module(s) (hiding data):", len(p.Modules)) + buf[1] = "" for _, mf := range p.Modules { buf = append(buf, diff --git a/v1/debug/breakpoint.go b/v1/debug/breakpoint.go index 03dd6246d1..3b3d94fd1d 100644 --- a/v1/debug/breakpoint.go +++ b/v1/debug/breakpoint.go @@ -90,7 +90,11 @@ func (bc *breakpointCollection) all() breakpointList { bc.mtx.Lock() defer bc.mtx.Unlock() - var bps breakpointList + count := 0 + for _, list := range bc.breakpoints { + count += len(list) + } + bps := make(breakpointList, 0, count) for _, list := range bc.breakpoints { bps = append(bps, list...) } diff --git a/v1/dependencies/deps_test.go b/v1/dependencies/deps_test.go index 8d260f9c04..3570ada71c 100644 --- a/v1/dependencies/deps_test.go +++ b/v1/dependencies/deps_test.go @@ -362,7 +362,8 @@ func TestDependencies(t *testing.T) { // Test that we get the same result by analyzing all the // rules separately. - var minRules, fullRules []ast.Ref + minRules := make([]ast.Ref, 0, len(mod.Rules)) + fullRules := make([]ast.Ref, 0, len(mod.Rules)) for _, rule := range mod.Rules { m, f := runDeps(t, rule) minRules = append(minRules, m...) diff --git a/v1/plugins/logs/encoder_test.go b/v1/plugins/logs/encoder_test.go index e44f27cb97..943957314c 100644 --- a/v1/plugins/logs/encoder_test.go +++ b/v1/plugins/logs/encoder_test.go @@ -518,7 +518,7 @@ func TestChunkEncoderAdaptive(t *testing.T) { func decodeChunks(t *testing.T, bs [][]byte) []EventV1 { t.Helper() - var events []EventV1 + events := make([]EventV1, 0, len(bs)) for _, chunk := range bs { e, err := newChunkDecoder(chunk).decode() if err != nil { diff --git a/v1/profiler/profiler.go b/v1/profiler/profiler.go index ffe8605b16..2efaea9e01 100644 --- a/v1/profiler/profiler.go +++ b/v1/profiler/profiler.go @@ -57,7 +57,7 @@ func (p *Profiler) ReportByFile() Report { report := Report{Files: map[string]*FileReport{}} for file, hits := range p.hits { - stats := []ExprStats{} + stats := make([]ExprStats, 0, len(hits)) for row, stat := range hits { if entry, ok := p.hitsByExprIndex[file][row]; ok { stat.NumGenExpr = len(entry) diff --git a/v1/rego/rego_test.go b/v1/rego/rego_test.go index 1f6ee78119..30f6770310 100644 --- a/v1/rego/rego_test.go +++ b/v1/rego/rego_test.go @@ -414,10 +414,10 @@ func assertPreparedEvalQueryEval(t *testing.T, pq PreparedEvalQuery, options []E func assertResultSet(t *testing.T, rs ResultSet, expected string) { t.Helper() - result := []any{} + result := make([]any, 0, len(rs)) for i := range rs { - values := []any{} + values := make([]any, 0, len(rs[i].Expressions)) for j := range rs[i].Expressions { values = append(values, rs[i].Expressions[j].Value) } diff --git a/v1/repl/repl.go b/v1/repl/repl.go index 465202f31b..4b1af65faf 100644 --- a/v1/repl/repl.go +++ b/v1/repl/repl.go @@ -1485,7 +1485,7 @@ func printHelpCommands(output io.Writer) { all := append(extra[:], builtin[:]...) // Compute max length of all command and topic names. - names := []string{} + names := make([]string, 0, len(all)+len(topics)) for _, x := range all { names = append(names, x.syntax()) diff --git a/v1/sdk/opa.go b/v1/sdk/opa.go index 152a640c3c..efc4cfcc6e 100644 --- a/v1/sdk/opa.go +++ b/v1/sdk/opa.go @@ -167,6 +167,7 @@ func (opa *OPA) configure(ctx context.Context, bs []byte, ready chan struct{}, b return err } + //nolint:prealloc // option list has known initial values, extended with opa.managerOpts opts := []func(*plugins.Manager){ plugins.Info(info), plugins.Logger(opa.logger), diff --git a/v1/tester/runner_test.go b/v1/tester/runner_test.go index cda2d9fa85..cef9111b73 100644 --- a/v1/tester/runner_test.go +++ b/v1/tester/runner_test.go @@ -726,7 +726,7 @@ func TestRunnerWithCustomBuiltin(t *testing.T) { t.Fatal(err) } - var results []*tester.Result + results := make([]*tester.Result, 0, 10) for r := range ch { results = append(results, r) diff --git a/v1/topdown/http_test.go b/v1/topdown/http_test.go index 058489bed3..5f52f77d7a 100644 --- a/v1/topdown/http_test.go +++ b/v1/topdown/http_test.go @@ -51,7 +51,7 @@ type Person struct { func TestHTTPGetRequest(t *testing.T) { t.Parallel() - var people []Person + people := make([]Person, 0, 1) // test data people = append(people, Person{ID: "1", Firstname: "John"}) @@ -71,7 +71,7 @@ func TestHTTPGetRequest(t *testing.T) { expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []any + body := make([]any, 0, 1) bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body @@ -122,7 +122,7 @@ func TestHTTPGetRequestTlsInsecureSkipVerify(t *testing.T) { "status_code": http.StatusOK, } - var body []any + body := make([]any, 0, 1) bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body @@ -558,7 +558,7 @@ func TestHTTPDeleteRequest(t *testing.T) { expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []any + body := make([]any, 0, 1) bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body @@ -3555,7 +3555,7 @@ var httpSendHelperRules = []string{ func TestSocketHTTPGetRequest(t *testing.T) { t.Parallel() - var people []Person + people := make([]Person, 0, 1) // test data people = append(people, Person{ID: "1", Firstname: "John"}) @@ -3598,7 +3598,7 @@ func TestSocketHTTPGetRequest(t *testing.T) { expectedResult["status"] = "200 OK" expectedResult["status_code"] = http.StatusOK - var body []any + body := make([]any, 0, 1) bodyMap := map[string]string{"id": "1", "firstname": "John"} body = append(body, bodyMap) expectedResult["body"] = body diff --git a/v1/topdown/json_bench_test.go b/v1/topdown/json_bench_test.go index e226c97d90..942355e2b4 100644 --- a/v1/topdown/json_bench_test.go +++ b/v1/topdown/json_bench_test.go @@ -366,7 +366,7 @@ func genRandom3LayerObjectJSONPatchListData(l1Keys, l2Keys, l3Keys, p int) ast.V depth := rand.Intn(3) + 1 // (max - min) + min method of getting a random range. // Random values for each path segment. - segments := []string{} + segments := make([]string, 0, 2*depth) for j := range depth { pathSegment := strconv.FormatInt(int64(rand.Intn(numKeys[j])), 10) segments = append(segments, "/", pathSegment) diff --git a/v1/topdown/tokens_test.go b/v1/topdown/tokens_test.go index e3dcf19a1b..20295c52d4 100644 --- a/v1/topdown/tokens_test.go +++ b/v1/topdown/tokens_test.go @@ -388,12 +388,10 @@ func TestTopDownJWTEncodeSignES512(t *testing.T) { note string rules []string } - var tests []test - - tests = append(tests, test{ + tests := []test{{ params.note, []string{fmt.Sprintf(`p = x { io.jwt.encode_sign_raw(%s, %s, %s, x) }`, params.input1, params.input2, params.input3)}, - }) + }} tc := tests[0] diff --git a/v1/topdown/topdown_test.go b/v1/topdown/topdown_test.go index f59efc8bc1..344f98f1ac 100644 --- a/v1/topdown/topdown_test.go +++ b/v1/topdown/topdown_test.go @@ -1946,7 +1946,7 @@ func compileModules(input []string) *ast.Compiler { func compileRules(imports []string, input []string, modules []string) (*ast.Compiler, error) { - is := []*ast.Import{} + is := make([]*ast.Import, 0, len(imports)) for _, i := range imports { is = append(is, &ast.Import{ Path: ast.MustParseTerm(i), @@ -1960,7 +1960,7 @@ func compileRules(imports []string, input []string, modules []string) (*ast.Comp Imports: is, } - rules := []*ast.Rule{} + rules := make([]*ast.Rule, 0, len(input)) for i := range input { rules = append(rules, ast.MustParseRuleWithOpts(input[i], popts)) rules[i].Module = m @@ -2096,7 +2096,7 @@ func runTopDownTestCaseWithContext(ctx context.Context, t *testing.T, data map[s options ...func(*Query) *Query) { t.Helper() - imports := []string{} + imports := make([]string, 0, len(data)) for k := range data { imports = append(imports, "data."+k) } @@ -2381,7 +2381,7 @@ func getTestNamespace() string { func dump(note string, modules map[string]*ast.Module, data any, docpath []string, input *ast.Term, exp any, requiresSort bool) { - moduleSet := []string{} + moduleSet := make([]string, 0, len(modules)) for _, module := range modules { moduleSet = append(moduleSet, string(bytes.ReplaceAll(format.MustAst(module), []byte("\t"), []byte(" ")))) } diff --git a/v1/types/types.go b/v1/types/types.go index 794f80ea2b..fc1db120a0 100644 --- a/v1/types/types.go +++ b/v1/types/types.go @@ -219,7 +219,7 @@ func (t *Array) toMap() map[string]any { func (t *Array) String() string { prefix := "array" - buf := []string{} + buf := make([]string, 0, len(t.static)) for _, tpe := range t.static { buf = append(buf, Sprint(tpe)) } diff --git a/v1/util/graph_test.go b/v1/util/graph_test.go index 9c05b3e31d..1e6c537e96 100644 --- a/v1/util/graph_test.go +++ b/v1/util/graph_test.go @@ -27,7 +27,7 @@ func newTestTraversal(g map[int][]int) *testTraversal { } func (t *testTraversal) Edges(x T) []T { - r := []T{} + r := make([]T, 0, len(t.g[x.(int)])) for _, v := range t.g[x.(int)] { r = append(r, v) }