From 0b8728be98e61b7c11a3dfd08bfff03b98e1553b Mon Sep 17 00:00:00 2001 From: Stephan Renatus Date: Thu, 22 Jan 2026 15:28:00 +0100 Subject: [PATCH] ast: fix String() of empty body (#8244) This gave me a panic, panic: runtime error: makeslice: cap out of range when printing some PE results. Signed-off-by: Stephan Renatus --- v1/ast/policy_test.go | 47 +++++++++++++++++++++++++++++++++++++++++ v1/ast/string_length.go | 2 +- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/v1/ast/policy_test.go b/v1/ast/policy_test.go index 786c7479ac..a1c2181885 100644 --- a/v1/ast/policy_test.go +++ b/v1/ast/policy_test.go @@ -91,6 +91,53 @@ func TestBodyEmptyJSON(t *testing.T) { } } +func TestBodyStringAndStringLength(t *testing.T) { + tests := []struct { + name string + body Body + wantLength int + }{ + { + name: "empty body", + body: Body{}, + wantLength: len(""), + }, + { + name: "nil body", + body: nil, + wantLength: len(""), + }, + { + name: "single expression", + body: MustParseBody("true"), + wantLength: len("true"), + }, + { + name: "two expressions", + body: MustParseBody("true; false"), + wantLength: len("true; false"), + }, + { + name: "three expressions", + body: MustParseBody("x = 1; y = 2; z = 3"), + wantLength: len("x = 1; y = 2; z = 3"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotLength := tt.body.StringLength() + if gotLength != tt.wantLength { + t.Errorf("Body.StringLength() = %d, want %d (body: %q)", gotLength, tt.wantLength, tt.body.String()) + } + + if gotLength < 0 { + t.Errorf("Body.StringLength() returned negative value: %d", gotLength) + } + }) + } +} + func TestPackageEquals(t *testing.T) { pkg1 := &Package{Path: RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")).Value.(Ref)} pkg2 := &Package{Path: RefTerm(VarTerm("foo"), StringTerm("bar"), StringTerm("baz")).Value.(Ref)} diff --git a/v1/ast/string_length.go b/v1/ast/string_length.go index e5abe2a6a5..fe9e8b5e0e 100644 --- a/v1/ast/string_length.go +++ b/v1/ast/string_length.go @@ -283,7 +283,7 @@ func (b Body) StringLength() (n int) { for _, expr := range b { n += expr.StringLength() + 2 // "; " } - return n - 2 // minus last "; " + return max(n-2, 0) // minus last "; " (if `n` isn't 0) } func (e *Expr) StringLength() (n int) {