in syntax/parse.go [979:1028]
func (p *parser) assignComments(n Node) {
// Leave early if there are no comments
if len(p.in.lineComments)+len(p.in.suffixComments) == 0 {
return
}
pre, post := flattenAST(n)
// Assign line comments to syntax immediately following.
line := p.in.lineComments
for _, x := range pre {
start, _ := x.Span()
switch x.(type) {
case *File:
continue
}
for len(line) > 0 && !start.isBefore(line[0].Start) {
x.AllocComments()
x.Comments().Before = append(x.Comments().Before, line[0])
line = line[1:]
}
}
// Remaining line comments go at end of file.
if len(line) > 0 {
n.AllocComments()
n.Comments().After = append(n.Comments().After, line...)
}
// Assign suffix comments to syntax immediately before.
suffix := p.in.suffixComments
for i := len(post) - 1; i >= 0; i-- {
x := post[i]
// Do not assign suffix comments to file
switch x.(type) {
case *File:
continue
}
_, end := x.Span()
if len(suffix) > 0 && end.isBefore(suffix[len(suffix)-1].Start) {
x.AllocComments()
x.Comments().Suffix = append(x.Comments().Suffix, suffix[len(suffix)-1])
suffix = suffix[:len(suffix)-1]
}
}
}