hcl/parser: literal elements in a list can have a lead comment

This commit is contained in:
Mitchell Hashimoto 2016-10-08 14:40:39 +08:00
parent 7d7bae6bc1
commit 8d4635e72c
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
3 changed files with 60 additions and 1 deletions

View File

@ -156,7 +156,8 @@ func (o *ObjectKey) Pos() token.Pos {
type LiteralType struct {
Token token.Token
// associated line comment, only when used in a list
// comment types, only used when in a list
LeadComment *CommentGroup
LineComment *CommentGroup
}

View File

@ -337,6 +337,12 @@ func (p *Parser) listType() (*ast.ListType, error) {
return nil, err
}
// If there is a lead comment, apply it
if p.leadComment != nil {
node.LeadComment = p.leadComment
p.leadComment = nil
}
l.Add(node)
needComma = true
case token.COMMA:

View File

@ -152,6 +152,58 @@ func TestListOfMaps_requiresComma(t *testing.T) {
}
}
func TestListType_leadComment(t *testing.T) {
var literals = []struct {
src string
comment []string
}{
{
`foo = [
1,
# bar
2,
3,
]`,
[]string{"", "# bar", ""},
},
}
for _, l := range literals {
p := newParser([]byte(l.src))
item, err := p.objectItem()
if err != nil {
t.Fatal(err)
}
list, ok := item.Val.(*ast.ListType)
if !ok {
t.Fatalf("node should be of type LiteralType, got: %T", item.Val)
}
if len(list.List) != len(l.comment) {
t.Fatalf("bad: %d", len(list.List))
}
for i, li := range list.List {
lt := li.(*ast.LiteralType)
comment := l.comment[i]
if (lt.LeadComment == nil) != (comment == "") {
t.Fatalf("bad: %#v", lt)
}
if comment == "" {
continue
}
actual := lt.LeadComment.List[0].Text
if actual != comment {
t.Fatalf("bad: %q %q", actual, comment)
}
}
}
}
func TestListType_lineComment(t *testing.T) {
var literals = []struct {
src string