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 <stephan.renatus@gmail.com>
This commit is contained in:
Stephan Renatus
2026-01-22 15:28:00 +01:00
committed by GitHub
parent 3ede316faa
commit 0b8728be98
2 changed files with 48 additions and 1 deletions
+47
View File
@@ -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)}
+1 -1
View File
@@ -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) {