From 48f0004e918c84c33a6db2717bf7c56b81fa4328 Mon Sep 17 00:00:00 2001 From: Charith Ellawala Date: Mon, 2 Dec 2024 13:32:42 +0000 Subject: [PATCH] Fix panic when parsing unattached comment The parser panics when there's a comment without anything to attach it to. This PR fixes that case. Signed-off-by: Charith Ellawala --- parser/parser.go | 11 ++++++++++- parser/parser_test.go | 8 ++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/parser/parser.go b/parser/parser.go index 5173393..88ae994 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -152,6 +152,10 @@ func (p *parser) parseDocumentBody(ctx *context) (ast.Node, error) { } func (p *parser) parseToken(ctx *context, tk *Token) (ast.Node, error) { + if tk == nil { + return nil, nil + } + switch tk.GroupType() { case TokenGroupMapKey, TokenGroupMapKeyValue: return p.parseMap(ctx) @@ -1063,7 +1067,12 @@ func (p *parser) parseDirective(ctx *context, g *TokenGroup) (*ast.DirectiveNode func (p *parser) parseComment(ctx *context) (ast.Node, error) { cm := p.parseHeadComment(ctx) - node, err := p.parseToken(ctx, ctx.currentToken()) + nextTok := ctx.currentToken() + if nextTok == nil { + return cm, nil + } + + node, err := p.parseToken(ctx, nextTok) if err != nil { return nil, err } diff --git a/parser/parser_test.go b/parser/parser_test.go index 14980b5..8d1db7b 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -1471,6 +1471,14 @@ foo: | # comment yaml: ` foo: > # comment x: 42 +`, + }, + { + name: "unattached comment", + yaml: ` +# This comment is in its own document +--- +a: b `, }, }