-
Notifications
You must be signed in to change notification settings - Fork 2
/
comment_scanner.go
103 lines (90 loc) · 2.49 KB
/
comment_scanner.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package packagesx
import (
"go/ast"
"go/token"
"sort"
"strings"
)
func NewCommentScanner(fileSet *token.FileSet, file *ast.File) *CommentScanner {
commentMap := ast.NewCommentMap(fileSet, file, file.Comments)
return &CommentScanner{
file: file,
CommentMap: commentMap,
}
}
type CommentScanner struct {
file *ast.File
CommentMap ast.CommentMap
}
func (scanner *CommentScanner) CommentsOf(targetNode ast.Node) string {
commentGroupList := scanner.CommentGroupListOf(targetNode)
return StringifyCommentGroup(commentGroupList...)
}
func (scanner *CommentScanner) CommentGroupListOf(targetNode ast.Node) (commentGroupList []*ast.CommentGroup) {
if targetNode == nil {
return
}
switch targetNode.(type) {
case *ast.File, *ast.Field, ast.Stmt, ast.Decl:
if comments, ok := scanner.CommentMap[targetNode]; ok {
commentGroupList = comments
}
case ast.Spec:
// Spec should merge with comments of its parent gen decl when empty
if comments, ok := scanner.CommentMap[targetNode]; ok {
commentGroupList = append(commentGroupList, comments...)
}
if len(commentGroupList) == 0 {
for node, comments := range scanner.CommentMap {
if genDecl, ok := node.(*ast.GenDecl); ok {
for _, spec := range genDecl.Specs {
if targetNode == spec {
commentGroupList = append(commentGroupList, comments...)
}
}
}
}
}
default:
// find nearest parent node which have comments
{
var deltaPos token.Pos
var parentNode ast.Node
deltaPos = -1
ast.Inspect(scanner.file, func(node ast.Node) bool {
switch node.(type) {
case *ast.Field, ast.Decl, ast.Spec, ast.Stmt:
if targetNode.Pos() >= node.Pos() && targetNode.End() <= node.End() {
nextDelta := targetNode.Pos() - node.Pos()
if deltaPos == -1 || (nextDelta <= deltaPos) {
deltaPos = nextDelta
parentNode = node
}
}
}
return true
})
if parentNode != nil {
commentGroupList = scanner.CommentGroupListOf(parentNode)
}
}
}
sort.Slice(commentGroupList, func(i, j int) bool {
return commentGroupList[i].Pos() < commentGroupList[j].Pos()
})
return
}
func StringifyCommentGroup(commentGroupList ...*ast.CommentGroup) (comments string) {
if len(commentGroupList) == 0 {
return ""
}
for _, commentGroup := range commentGroupList {
for _, line := range strings.Split(commentGroup.Text(), "\n") {
if strings.HasPrefix(line, "go:") {
continue
}
comments = comments + "\n" + line
}
}
return strings.TrimSpace(comments)
}