-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathcursor.go
More file actions
114 lines (90 loc) · 2.23 KB
/
Copy pathcursor.go
File metadata and controls
114 lines (90 loc) · 2.23 KB
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
104
105
106
107
108
109
110
111
112
113
114
package wsl
import (
"go/ast"
)
// Cursor holds a list of statements and a pointer to where in the list we are.
// Each block gets a new cursor and can be used to check previous or coming
// statements.
type Cursor struct {
currentIdx int
statements []ast.Stmt
checkType CheckType
// rbraceLine is the source line of the enclosing block's closing brace.
// It is used to avoid false positives when checking for trailing comments:
// an inline comment that sits on the same line as the closing brace belongs
// to the brace itself, not to the last statement inside the block.
// Zero means the enclosing block boundary is unknown (e.g. case clauses).
rbraceLine int
}
// NewCursor creates a new cursor with a given list of statements.
func NewCursor(statements []ast.Stmt) *Cursor {
return &Cursor{
currentIdx: -1,
statements: statements,
}
}
// NewBlockCursor creates a cursor for the statements of a known block, recording
// the source line of the block's closing brace so that trailing-comment checks
// can ignore inline comments that sit on the brace itself.
func NewBlockCursor(statements []ast.Stmt, rbraceLine int) *Cursor {
return &Cursor{
currentIdx: -1,
statements: statements,
rbraceLine: rbraceLine,
}
}
func (c *Cursor) SetChecker(ct CheckType) {
c.checkType = ct
}
func (c *Cursor) NextNode() ast.Node {
defer c.Save()()
var nextNode ast.Node
if c.Next() {
nextNode = c.Stmt()
}
return nextNode
}
func (c *Cursor) Next() bool {
if c.currentIdx >= len(c.statements)-1 {
return false
}
c.currentIdx++
return true
}
func (c *Cursor) Previous() bool {
if c.currentIdx <= 0 {
return false
}
c.currentIdx--
return true
}
func (c *Cursor) PreviousNode() ast.Node {
defer c.Save()()
var previousNode ast.Node
if c.Previous() {
previousNode = c.Stmt()
}
return previousNode
}
func (c *Cursor) Stmt() ast.Stmt {
return c.statements[c.currentIdx]
}
func (c *Cursor) Save() func() {
idx := c.currentIdx
return func() {
c.currentIdx = idx
}
}
func (c *Cursor) Len() int {
return len(c.statements)
}
func (c *Cursor) Nth(n int) ast.Stmt {
return c.statements[n]
}
func (c *Cursor) NthPrevious(n int) ast.Node {
idx := c.currentIdx - n
if idx < 0 {
return nil
}
return c.statements[idx]
}