-
Notifications
You must be signed in to change notification settings - Fork 5
/
printf.go
252 lines (227 loc) · 5.78 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package printf
import (
"strconv"
"strings"
"unicode/utf8"
)
// Copied from golang.org/x/tools
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
type printVerb struct {
verb rune // User may provide verb through Formatter; could be a rune.
flags string // known flags are all ASCII
}
// Common flag sets for printf verbs.
const (
noFlag = ""
numFlag = " -+.0"
sharpNumFlag = " -+.0#"
allFlags = " -+.0#"
)
// printVerbs identifies which flags are known to printf for each verb.
var printVerbs = []printVerb{
// '-' is a width modifier, always valid.
// '.' is a precision for float, max width for strings.
// '+' is required sign for numbers, Go format for %v.
// '#' is alternate format for several verbs.
// ' ' is spacer for numbers
{'%', noFlag},
{'b', sharpNumFlag},
{'c', "-"},
{'d', numFlag},
{'e', sharpNumFlag},
{'E', sharpNumFlag},
{'f', sharpNumFlag},
{'F', sharpNumFlag},
{'g', sharpNumFlag},
{'G', sharpNumFlag},
{'o', sharpNumFlag},
{'O', sharpNumFlag},
{'p', "-#"},
{'q', " -+.0#"},
{'s', " -+.0"},
{'t', "-"},
{'T', "-"},
{'U', "-#"},
{'v', allFlags},
{'w', allFlags},
{'x', sharpNumFlag},
{'X', sharpNumFlag},
}
// formatState holds the parsed representation of a printf directive such as "%3.*[4]d".
// It is constructed by parsePrintfVerb.
type formatState struct {
verb rune // the format verb: 'd' for "%d"
format string // the full format directive from % through verb, "%.3d".
flags []byte // the list of # + etc.
// Used only during parse.
hasIndex bool // Whether the argument is indexed.
indexPending bool // Whether we have an indexed argument that has not resolved.
nbytes int // number of bytes of the format string consumed.
}
// parseFlags accepts any printf flags.
func (s *formatState) parseFlags() {
for s.nbytes < len(s.format) {
switch c := s.format[s.nbytes]; c {
case '#', '0', '+', '-', ' ':
s.flags = append(s.flags, c)
s.nbytes++
default:
return
}
}
}
// scanNum advances through a decimal number if present.
func (s *formatState) scanNum() {
for ; s.nbytes < len(s.format); s.nbytes++ {
c := s.format[s.nbytes]
if c < '0' || '9' < c {
return
}
}
}
func stringIndexAt(s, substr string, start int) int {
idx := strings.Index(s[start:], substr)
if idx < 0 {
return idx
}
return idx + start
}
// parseIndex scans an index expression. It returns false if there is a syntax error.
func (s *formatState) parseIndex() bool {
if s.nbytes == len(s.format) || s.format[s.nbytes] != '[' {
return true
}
// Argument index present.
s.nbytes++ // skip '['
start := s.nbytes
s.scanNum()
ok := true
if s.nbytes == len(s.format) || s.nbytes == start || s.format[s.nbytes] != ']' {
ok = false
s.nbytes = stringIndexAt(s.format, "]", start)
if s.nbytes < 0 {
return false
}
}
arg32, err := strconv.ParseInt(s.format[start:s.nbytes], 10, 32)
if err != nil || !ok || arg32 <= 0 {
return false
}
s.nbytes++ // skip ']'
s.hasIndex = true
s.indexPending = true
return true
}
// parseNum scans a width or precision (or *).
func (s *formatState) parseNum() {
if s.nbytes < len(s.format) && s.format[s.nbytes] == '*' {
if s.indexPending { // Absorb it.
s.indexPending = false
}
s.nbytes++
} else {
s.scanNum()
}
}
// parsePrecision scans for a precision. It returns false if there's a bad index expression.
func (s *formatState) parsePrecision() bool {
// If there's a period, there may be a precision.
if s.nbytes < len(s.format) && s.format[s.nbytes] == '.' {
s.flags = append(s.flags, '.') // Treat precision as a flag.
s.nbytes++
if !s.parseIndex() {
return false
}
s.parseNum()
}
return true
}
// parsePrintfVerb looks the formatting directive that begins the format string
// and returns a formatState that encodes what the directive wants, without looking
// at the actual arguments present in the call. The result is nil if there is an error.
func parsePrintfVerb(format string) *formatState {
state := &formatState{
format: format,
flags: make([]byte, 0, 5), //nolint:gomnd
nbytes: 1, // There's guaranteed to be a percent sign.
}
// There may be flags.
state.parseFlags()
// There may be an index.
if !state.parseIndex() {
return nil
}
// There may be a width.
state.parseNum()
// There may be a precision.
if !state.parsePrecision() {
return nil
}
// Now a verb, possibly prefixed by an index (which we may already have).
if !state.indexPending && !state.parseIndex() {
return nil
}
if state.nbytes == len(state.format) {
// missing verb at end of string
return nil
}
verb, w := utf8.DecodeRuneInString(state.format[state.nbytes:])
state.verb = verb
state.nbytes += w
state.format = state.format[:state.nbytes]
return state
}
func containsAll(s string, pattern []byte) bool {
for _, c := range pattern {
if !strings.ContainsRune(s, rune(c)) {
return false
}
}
return true
}
func isPrintfArg(state *formatState) bool {
var v printVerb
found := false
// Linear scan is fast enough for a small list.
for _, v = range printVerbs {
if v.verb == state.verb {
found = true
break
}
}
if !found {
// unknown verb, just skip
return false
}
if !containsAll(v.flags, state.flags) {
// unrecognized format flag, just skip
return false
}
return true
}
func IsPrintfLike(format string) (firstSpecifier string, ok bool) {
if !strings.Contains(format, "%") {
return "", false
}
for i, w := 0, 0; i < len(format); i += w {
w = 1
if format[i] != '%' {
continue
}
state := parsePrintfVerb(format[i:])
if state == nil {
return "", false
}
w = len(state.format)
if !isPrintfArg(state) {
return "", false
}
if !ok {
firstSpecifier = state.format
ok = true
}
}
return
}