-
Notifications
You must be signed in to change notification settings - Fork 17
/
printf.go
134 lines (120 loc) · 2.18 KB
/
printf.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package errorlint
import (
"fmt"
"io"
"strconv"
"strings"
)
func verbOrder(verbs []verb, numArgs int) [][]verb {
orderedVerbs := make([][]verb, numArgs)
i := 0
for _, v := range verbs {
if v.index != -1 {
i = v.index - 1
}
if i >= len(orderedVerbs) {
continue
}
orderedVerbs[i] = append(orderedVerbs[i], v)
verbs = verbs[1:]
i++
}
return orderedVerbs
}
type verb struct {
format string
index int
}
type printfParser struct {
str string
}
func (pp *printfParser) ParseAllVerbs() ([]verb, error) {
verbs := []verb{}
for {
verb, err := pp.parseVerb()
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
verbs = append(verbs, *verb)
}
return verbs, nil
}
func (pp *printfParser) parseVerb() (*verb, error) {
if err := pp.skipToPercent(); err != nil {
return nil, err
}
if pp.next() != '%' {
return nil, fmt.Errorf("expected '%%'")
}
index := -1
for {
switch pp.peek() {
case '%':
pp.next()
return pp.parseVerb()
case '+', '#':
pp.next()
continue
case '[':
var err error
index, err = pp.parseIndex()
if err != nil {
return nil, err
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.':
pp.parsePrecision()
case 0:
return nil, io.EOF
}
break
}
format := pp.next()
return &verb{format: string(format), index: index}, nil
}
func (pp *printfParser) parseIndex() (int, error) {
if pp.next() != '[' {
return -1, fmt.Errorf("expected '['")
}
end := strings.Index(pp.str, "]")
if end == -1 {
return -1, fmt.Errorf("unterminated indexed verb")
}
index, err := strconv.Atoi(pp.str[:end])
if err != nil {
return -1, err
}
pp.str = pp.str[end+1:]
return index, nil
}
func (pp *printfParser) parsePrecision() {
for {
if r := pp.peek(); (r < '0' || '9' < r) && r != '.' {
break
}
pp.next()
}
}
func (pp *printfParser) skipToPercent() error {
i := strings.Index(pp.str, "%")
if i == -1 {
return io.EOF
}
pp.str = pp.str[i:]
return nil
}
func (pp *printfParser) peek() rune {
if len(pp.str) == 0 {
return 0
}
return rune(pp.str[0])
}
func (pp *printfParser) next() rune {
if len(pp.str) == 0 {
return 0
}
r := rune(pp.str[0])
pp.str = pp.str[1:]
return r
}