Skip to content

Commit

Permalink
fix: empty document should not panic on String() (#630)
Browse files Browse the repository at this point in the history
fixes #629
  • Loading branch information
bcho authored Jan 31, 2025
1 parent 5bac4f3 commit 6f80c57
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
4 changes: 3 additions & 1 deletion ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -576,7 +576,9 @@ func (d *DocumentNode) String() string {
if d.Start != nil {
doc = append(doc, d.Start.Value)
}
doc = append(doc, d.Body.String())
if d.Body != nil {
doc = append(doc, d.Body.String())
}
if d.End != nil {
doc = append(doc, d.End.Value)
}
Expand Down
43 changes: 42 additions & 1 deletion parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

func TestParser(t *testing.T) {
sources := []string{
"",
"null\n",
"0_",
"{}\n",
Expand Down Expand Up @@ -144,12 +145,52 @@ foo: zzz
`,
}
for _, src := range sources {
if _, err := parser.Parse(lexer.Tokenize(src), 0); err != nil {
f, err := parser.Parse(lexer.Tokenize(src), 0)
if err != nil {
t.Fatalf("parse error: source [%s]: %+v", src, err)
}
_ = f.String() // ensure no panic
}
}

func TestParseEmptyDocument(t *testing.T) {
t.Run("empty document", func(t *testing.T) {
f, err := parser.ParseBytes([]byte(""), parser.ParseComments)
if err != nil {
t.Fatal(err)
}
got := f.String()
expected := "\n"
if got != expected {
t.Fatalf("failed to parse comment:\nexpected:\n%q\ngot:\n%q", expected, got)
}
})

t.Run("empty document with comment (parse comment = off)", func(t *testing.T) {
f, err := parser.ParseBytes([]byte("# comment"), 0)
if err != nil {
t.Fatal(err)
}
got := f.String()
expected := "\n"
if got != expected {
t.Fatalf("failed to parse comment:\nexpected:\n%q\ngot:\n%q", expected, got)
}
})

t.Run("empty document with comment (parse comment = on)", func(t *testing.T) {
f, err := parser.ParseBytes([]byte("# comment"), parser.ParseComments)
if err != nil {
t.Fatal(err)
}
got := f.String()
expected := "# comment\n"
if got != expected {
t.Fatalf("failed to parse comment:\nexpected:\n%q\ngot:\n%q", expected, got)
}
})
}

func TestParseComplicatedDocument(t *testing.T) {
tests := []struct {
source string
Expand Down

0 comments on commit 6f80c57

Please sign in to comment.