-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
457 lines (349 loc) · 10.3 KB
/
parser.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package argh
import (
"fmt"
"io"
"strings"
)
type parser struct {
s *Scanner
cfg *ParserConfig
errors ParserErrorList
tok Token
lit string
pos Pos
buffered bool
}
type ParseTree struct {
Nodes []Node `json:"nodes"`
}
func ParseArgs(args []string, pCfg *ParserConfig) (*ParseTree, error) {
p := &parser{}
if err := p.init(
strings.NewReader(strings.Join(args, string(nul))),
pCfg,
); err != nil {
return nil, err
}
tracef("ParseArgs(...) parser=%+#v", p)
return p.parseArgs()
}
func (p *parser) addError(msg string) {
p.errors.Add(Position{Column: int(p.pos)}, msg)
}
func (p *parser) init(r io.Reader, pCfg *ParserConfig) error {
p.errors = ParserErrorList{}
if pCfg == nil {
return fmt.Errorf("nil parser config: %w", Err)
}
p.cfg = pCfg
p.s = NewScanner(r, pCfg.ScannerConfig)
p.next()
return nil
}
func (p *parser) parseArgs() (*ParseTree, error) {
if p.errors.Len() != 0 {
tracef("parseArgs() bailing due to initial error")
return nil, p.errors.Err()
}
tracef("parseArgs() parsing %q as program command; cfg=%+#v", p.lit, p.cfg.Prog)
prog, err := p.parseCommand(p.cfg.Prog)
if err != nil {
return nil, err
}
tracef("parseArgs() top level node is %T", prog)
nodes := []Node{prog}
if v := p.parsePassthrough(); v != nil {
tracef("parseArgs() appending passthrough argument %v", v)
nodes = append(nodes, v)
}
tracef("parseArgs() returning ParseTree")
return &ParseTree{Nodes: nodes}, p.errors.Err()
}
func (p *parser) next() {
tracef("next() before scan: %v %q %v", p.tok, p.lit, p.pos)
p.tok, p.lit, p.pos = p.s.Scan()
tracef("next() after scan: %v %q %v", p.tok, p.lit, p.pos)
}
func (p *parser) parseCommand(cCfg *CommandConfig) (Node, error) {
tracef("parseCommand(%+#v)", cCfg)
node := &Command{
Name: p.lit,
}
values := map[string]string{}
nodes := []Node{}
identIndex := 0
for i := 0; p.tok != EOL; i++ {
if !p.buffered {
tracef("parseCommand(...) buffered=false; scanning next")
p.next()
}
p.buffered = false
tracef("parseCommand(...) for=%d values=%+#v", i, values)
tracef("parseCommand(...) for=%d nodes=%+#v", i, nodes)
tracef("parseCommand(...) for=%d tok=%s lit=%q pos=%v", i, p.tok, p.lit, p.pos)
tracef("parseCommand(...) cCfg=%+#v", cCfg)
if subCfg, ok := cCfg.GetCommandConfig(p.lit); ok {
subCommand := p.lit
subNode, err := p.parseCommand(&subCfg)
if err != nil {
return node, err
}
nodes = append(nodes, subNode)
tracef("parseCommand(...) breaking after sub-command=%v", subCommand)
break
}
switch p.tok {
case ARG_DELIMITER:
tracef("parseCommand(...) handling %s", p.tok)
nodes = append(nodes, &ArgDelimiter{})
continue
case IDENT, STDIN_FLAG:
tracef("parseCommand(...) handling %s", p.tok)
if cCfg.NValue.Contains(identIndex) {
name := fmt.Sprintf("%d", identIndex)
tracef("parseCommand(...) checking for name of identIndex=%d", identIndex)
if len(cCfg.ValueNames) > identIndex {
name = cCfg.ValueNames[identIndex]
tracef("parseCommand(...) setting name=%s from config value names", name)
} else if len(cCfg.ValueNames) == 1 && (cCfg.NValue == OneOrMoreValue || cCfg.NValue == ZeroOrMoreValue) {
name = fmt.Sprintf("%s.%d", cCfg.ValueNames[0], identIndex)
tracef("parseCommand(...) setting name=%s from repeating value name", name)
}
values[name] = p.lit
}
if p.tok == STDIN_FLAG {
nodes = append(nodes, &StdinFlag{})
} else {
nodes = append(nodes, &Ident{Literal: p.lit})
}
identIndex++
case LONG_FLAG, SHORT_FLAG, COMPOUND_SHORT_FLAG:
tok := p.tok
flagNode, err := p.parseFlag(cCfg.Flags)
if err != nil {
return node, err
}
tracef("parseCommand(...) appending %s node=%+#v", tok, flagNode)
nodes = append(nodes, flagNode)
case ASSIGN:
tracef("parseCommand(...) error on bare %s", p.tok)
p.addError("invalid bare assignment")
break
default:
tracef("parseCommand(...) breaking on %s", p.tok)
break
}
}
if len(nodes) > 0 {
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
if cCfg.On != nil {
tracef("parseCommand(...) calling command config handler for node=%+#v", node)
if err := cCfg.On(*node); err != nil {
return node, err
}
} else {
tracef("parseCommand(...) no command config handler for node=%+#v", node)
}
tracef("parseCommand(...) returning node=%+#v", node)
return node, nil
}
func (p *parser) parseIdent() Node {
node := &Ident{Literal: p.lit}
return node
}
func (p *parser) parseFlag(flags *Flags) (Node, error) {
switch p.tok {
case SHORT_FLAG:
tracef("parseFlag(...) parsing short flag with config=%+#v", flags)
return p.parseShortFlag(flags)
case LONG_FLAG:
tracef("parseFlag(...) parsing long flag with config=%+#v", flags)
return p.parseLongFlag(flags)
case COMPOUND_SHORT_FLAG:
tracef("parseFlag(...) parsing compound short flag with config=%+#v", flags)
return p.parseCompoundShortFlag(flags)
}
panic(fmt.Sprintf("token %v cannot be parsed as flag", p.tok))
}
func (p *parser) parseShortFlag(flags *Flags) (Node, error) {
node := &Flag{Name: string(p.lit[1])}
flCfg, ok := flags.Get(node.Name)
if !ok {
errMsg := fmt.Sprintf("unknown flag %[1]q", node.Name)
p.addError(errMsg)
return node, &FlagError{
Pos: Position{Column: int(p.pos)},
Node: *node,
Msg: errMsg,
}
}
return p.parseConfiguredFlag(node, flCfg, nil)
}
func (p *parser) parseLongFlag(flags *Flags) (Node, error) {
node := &Flag{Name: string(p.lit[2:])}
flCfg, ok := flags.Get(node.Name)
if !ok {
errMsg := fmt.Sprintf("unknown flag %[1]q", node.Name)
p.addError(errMsg)
return node, &FlagError{
Pos: Position{Column: int(p.pos)},
Node: *node,
Msg: errMsg,
}
}
return p.parseConfiguredFlag(node, flCfg, nil)
}
func (p *parser) parseCompoundShortFlag(flags *Flags) (Node, error) {
unparsedFlags := []*Flag{}
unparsedFlagConfigs := []FlagConfig{}
withoutFlagPrefix := p.lit[1:]
for _, r := range withoutFlagPrefix {
node := &Flag{Name: string(r)}
flCfg, ok := flags.Get(node.Name)
if !ok {
errMsg := fmt.Sprintf("unknown flag %[1]q", node.Name)
p.addError(errMsg)
return node, &FlagError{
Pos: Position{Column: int(p.pos)},
Node: *node,
Msg: errMsg,
}
}
unparsedFlags = append(unparsedFlags, node)
unparsedFlagConfigs = append(unparsedFlagConfigs, flCfg)
}
flagNodes := []Node{}
for i, node := range unparsedFlags {
flCfg := unparsedFlagConfigs[i]
if i != len(unparsedFlags)-1 {
// NOTE: if a compound short flag is configured to accept
// more than zero values but is not the last flag in the
// group, it will be parsed with an override NValue of
// ZeroValue so that it does not consume the next token.
if flCfg.NValue.Required() {
errMsg := fmt.Sprintf(
"short flag %[1]q before end of compound group expects value",
node.Name,
)
p.addError(
errMsg,
)
return nil, fmt.Errorf(errMsg+": %[1]w", Err)
}
flagNode, err := p.parseConfiguredFlag(node, flCfg, zeroValuePtr)
if err != nil {
return nil, err
}
flagNodes = append(flagNodes, flagNode)
continue
}
flagNode, err := p.parseConfiguredFlag(node, flCfg, nil)
if err != nil {
return nil, err
}
flagNodes = append(flagNodes, flagNode)
}
return &CompoundShortFlag{Nodes: flagNodes}, nil
}
func (p *parser) parseConfiguredFlag(node *Flag, flCfg FlagConfig, nValueOverride *NValue) (Node, error) {
values := map[string]string{}
nodes := []Node{}
atExit := func() (*Flag, error) {
if len(nodes) > 0 {
node.Nodes = nodes
}
if len(values) > 0 {
node.Values = values
}
if flCfg.On != nil {
tracef("parseConfiguredFlag(...) calling flag config handler for node=%+#[1]v", node)
if err := flCfg.On(*node); err != nil {
return nil, err
}
} else {
tracef("parseConfiguredFlag(...) no flag config handler for node=%+#[1]v", node)
}
return node, nil
}
identIndex := 0
for i := 0; p.tok != EOL; i++ {
if nValueOverride != nil && !(*nValueOverride).Contains(identIndex) {
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, *nValueOverride)
break
}
if !flCfg.NValue.Contains(identIndex) {
tracef("parseConfiguredFlag(...) identIndex=%d exceeds expected=%v; breaking", identIndex, flCfg.NValue)
break
}
p.next()
switch p.tok {
case ARG_DELIMITER:
nodes = append(nodes, &ArgDelimiter{})
continue
case ASSIGN:
nodes = append(nodes, &Assign{})
continue
case IDENT, STDIN_FLAG, MULTI_VALUE_DELIMITER:
name := fmt.Sprintf("%d", identIndex)
tracef("parseConfiguredFlag(...) checking for name of identIndex=%d", identIndex)
if len(flCfg.ValueNames) > identIndex {
name = flCfg.ValueNames[identIndex]
tracef("parseConfiguredFlag(...) setting name=%s from config value names", name)
} else if len(flCfg.ValueNames) == 1 && (flCfg.NValue == OneOrMoreValue || flCfg.NValue == ZeroOrMoreValue) {
name = fmt.Sprintf("%s.%d", flCfg.ValueNames[0], identIndex)
tracef("parseConfiguredFlag(...) setting name=%s from repeating value name", name)
} else {
tracef("parseConfiguredFlag(...) setting name=%s", name)
}
if p.tok != MULTI_VALUE_DELIMITER {
values[name] = p.lit
}
addNode := func(node Node) {
if len(nodes) > 0 {
if v, ok := nodes[len(nodes)-1].(*MultiIdent); ok {
v.Nodes = append(v.Nodes, node)
return
}
}
nodes = append(nodes, node)
}
if p.tok == STDIN_FLAG {
addNode(&StdinFlag{})
} else if p.tok == MULTI_VALUE_DELIMITER {
if len(nodes) > 0 {
if v, ok := nodes[len(nodes)-1].(*Ident); ok {
nodes[len(nodes)-1] = &MultiIdent{Nodes: []Node{v}}
} else if v, ok := nodes[len(nodes)-1].(*StdinFlag); ok {
nodes[len(nodes)-1] = &MultiIdent{Nodes: []Node{v}}
}
} else {
nodes = append(nodes, &MultiIdent{Nodes: []Node{}})
}
} else {
addNode(&Ident{Literal: p.lit})
}
if p.tok != MULTI_VALUE_DELIMITER {
identIndex++
}
default:
tracef("parseConfiguredFlag(...) breaking on %s %q %v; setting buffered=true", p.tok, p.lit, p.pos)
p.buffered = true
return atExit()
}
}
return atExit()
}
func (p *parser) parsePassthrough() Node {
nodes := []Node{}
for ; p.tok != EOL; p.next() {
nodes = append(nodes, &Ident{Literal: p.lit})
}
if len(nodes) == 0 {
return nil
}
return &PassthroughArgs{Nodes: nodes}
}