-
Notifications
You must be signed in to change notification settings - Fork 34
/
pkgx_comment.go
75 lines (69 loc) · 1.48 KB
/
pkgx_comment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package pkgx
import (
"go/ast"
"go/token"
"sort"
)
type CommentScanner struct {
*ast.File
ast.CommentMap
}
func NewCommentScanner(fs *token.FileSet, f *ast.File) *CommentScanner {
return &CommentScanner{
File: f,
CommentMap: ast.NewCommentMap(fs, f, f.Comments),
}
}
func (c *CommentScanner) CommentsOf(n ast.Node) string {
return StringifyCommentGroup(c.CommentGroupsOf(n)...)
}
func (c *CommentScanner) CommentGroupsOf(n ast.Node) (cgs []*ast.CommentGroup) {
if n == nil {
return
}
switch n.(type) {
case *ast.File, *ast.Field, ast.Stmt, ast.Decl:
if comments, ok := c.CommentMap[n]; ok {
cgs = comments
}
case ast.Spec:
if comments, ok := c.CommentMap[n]; ok {
cgs = append(cgs, comments...)
}
if len(cgs) == 0 {
for node, comments := range c.CommentMap {
if decl, ok := node.(*ast.GenDecl); ok {
for _, spec := range decl.Specs {
if n == spec {
cgs = append(cgs, comments...)
}
}
}
}
}
default:
var (
pos token.Pos = -1
parent ast.Node
)
ast.Inspect(c.File, func(node ast.Node) bool {
switch node.(type) {
case *ast.Field, ast.Stmt, ast.Decl, ast.Spec:
if n.Pos() >= node.Pos() && n.End() <= node.End() {
next := n.Pos() - node.Pos()
if pos == -1 || next <= pos {
pos, parent = next, node
}
}
}
return true
})
if parent != nil {
cgs = c.CommentGroupsOf(parent)
}
}
sort.Slice(cgs, func(i, j int) bool {
return cgs[i].Pos() < cgs[j].Pos()
})
return
}