Skip to content

Commit 5d9d844

Browse files
Handle comments at the end of an array (#151)
1 parent bb2929c commit 5d9d844

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

literals.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,16 @@ func (l *Literal) parse(p *Parser) error {
103103
} else {
104104
l.Comment.Merge(nc)
105105
}
106-
// continue with remaining entries
106+
// peek at next token to see if it's structural (indicating end of current context)
107+
// if so, don't recurse, just return with comment set
108+
nextPos, nextTok, nextLit := p.next()
109+
if nextTok == tRIGHTSQUARE || nextTok == tRIGHTCURLY || nextTok == tSEMICOLON || nextTok == tCOMMA {
110+
// put it back and return - let the caller handle these structural tokens
111+
p.nextPut(nextPos, nextTok, nextLit)
112+
return nil
113+
}
114+
// put it back and continue with remaining entries (could be another comment or a literal)
115+
p.nextPut(nextPos, nextTok, nextLit)
107116
return l.parse(p)
108117
}
109118
if tok == tLEFTSQUARE {
@@ -125,6 +134,25 @@ func (l *Literal) parse(p *Parser) error {
125134
if err := e.parse(p); err != nil {
126135
return err
127136
}
137+
// if this is a comment-only literal, don't add it to array
138+
// but keep reading to attach comment to next literal
139+
if e.Comment != nil && e.Source == "" && e.Array == nil && e.OrderedMap == nil {
140+
// check what comes next
141+
_, tok, lit := p.next()
142+
if tok == tRIGHTSQUARE {
143+
// array ends with comment, just break
144+
break
145+
}
146+
if tok == tCOMMA {
147+
// comma after comment, continue to next element
148+
continue
149+
}
150+
// put back the token
151+
p.nextPut(pos, tok, lit)
152+
// continue loop - next iteration will parse the real literal
153+
// and the comment will already be in 'e' from the recursive parse() call
154+
continue
155+
}
128156
array = append(array, e)
129157
_, tok, lit := p.next()
130158
if tok == tCOMMA {
@@ -133,6 +161,11 @@ func (l *Literal) parse(p *Parser) error {
133161
if tok == tRIGHTSQUARE {
134162
break
135163
}
164+
// handle comments inside arrays
165+
if tok == tCOMMENT {
166+
p.nextPut(pos, tok, lit)
167+
continue
168+
}
136169
return p.unexpected(lit, ", or ]", l)
137170
}
138171
l.Array = array

option_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,7 @@ func TestCommentInsideArray(t *testing.T) {
740740
{has : [
741741
// comment on test
742742
"test"
743+
// ignored comment at the end
743744
]}
744745
]
745746
};
@@ -768,6 +769,7 @@ func TestParseBracedFullIdent(t *testing.T) {
768769
t.Errorf("got [%[1]v:%[1]T] want [%[2]v:%[2]T]", got, want)
769770
}
770771
}
772+
771773
func TestParseBracedFullIdentWithLeadingDot(t *testing.T) {
772774
src := `some.(.like).it.(.hot) = API_OPAQUE;`
773775
p := newParserOn(src)

0 commit comments

Comments
 (0)