Repository navigation
Expand file tree
/
Copy pathparse.go
More file actions
558 lines (510 loc) · 13.4 KB
/
Copy pathparse.go
File metadata and controls
558 lines (510 loc) · 13.4 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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
package main
// Putting the words back together into the shape the shell would run them
// in.
//
// The shape is the point. A line with curl on it means one thing on its
// own and another when the pipe after it goes to sh, and the only
// difference between those two is which side of a pipeline each command
// sits on. The same goes for a subshell, a function body that nothing ever
// calls, and the else branch that only runs on a machine without the tool
// already installed. Flattening a script into a list of commands loses all
// of that, and losing it is how a reader ends up frightened of an installer
// that is fine, or comfortable with one that is not.
//
// This is a subset of the grammar and it is chosen rather than partial.
// Everything that changes what a command can do is in: pipelines, lists,
// subshells, groups, functions, if, for, while, until and case, with the
// redirections and here-documents that hang off them. What is left out is
// the parts that change how a value comes out rather than what runs, and
// where a wrong guess costs one line of a report rather than a wrong
// answer.
type Node interface{ node() }
// Cmd is one command with its arguments, the assignments in front of it,
// and the redirections hanging off it.
type Cmd struct {
Words []Token
Assigns []Assign
Redirects []Redirect
Line int
}
type Assign struct {
Name string
Value Token
Line int
}
type Redirect struct {
Op string
Target Token
// Heredoc is the body when Op is << or <<-, which is how a script
// writes a file it did not download.
Heredoc string
// Frozen is a here-document whose tag was quoted, so nothing inside it
// was expanded and what is written is what lands on disk.
Frozen bool
}
// Pipeline is one or more commands joined by pipes. Everything after the
// first is being fed whatever the one before it printed.
type Pipeline struct {
Cmds []Node
Line int
}
// List is pipelines joined by ;, &&, || or &.
type List struct{ Items []Item }
type Item struct {
Node Node
// After is the operator that followed this item: "&&", "||", ";", "&"
// or "" at the end.
After string
}
type If struct {
Cond Node
Then Node
Else Node
Line int
}
type Loop struct {
// Name is empty for while and until, and the variable for a for loop.
Name string
// In is what a for loop walks over, which is often a list of URLs or
// of files about to be written.
In []Token
Cond Node
Body Node
Until bool
Line int
}
type Case struct {
Word Token
Clauses []Clause
Line int
}
type Clause struct {
Patterns []Token
Body Node
}
// Func is a function definition. Its body is parsed and kept, and whether
// anything ever calls it is a separate question answered later.
type Func struct {
Name string
Body Node
Line int
}
// Subshell is ( ... ) and Group is { ... ; }. They are kept apart because
// only one of them can change the directory out from under what follows.
type Subshell struct{ Body Node }
type Group struct{ Body Node }
func (*Cmd) node() {}
func (*Pipeline) node() {}
func (*List) node() {}
func (*If) node() {}
func (*Loop) node() {}
func (*Case) node() {}
func (*Func) node() {}
func (*Subshell) node() {}
func (*Group) node() {}
type parser struct {
tokens []Token
at int
Gaps []string
// deep guards against a script that nests further than any real one,
// which is a hand made file rather than an installer.
deep int
}
const deepest = 200
// Parse reads a script and gives back what it would run.
func Parse(src string) (Node, []string) {
tokens, gaps := lex(src)
p := &parser{tokens: tokens, Gaps: gaps}
body := p.list(nil)
return body, p.Gaps
}
func (p *parser) here() Token { return p.tokens[p.at] }
func (p *parser) done() bool { return p.here().Kind == End }
func (p *parser) next() Token { t := p.tokens[p.at]; p.at++; return t }
func (p *parser) back() { p.at-- }
func (p *parser) skipNewlines() {
for p.here().Kind == Newline || (p.here().Kind == Op && p.here().Text == ";") {
p.at++
}
}
// isWord says whether the token here is a bare word with this text, which
// is how the shell spells its keywords: fi and done are words, not
// operators, and a file called done is also a word.
func (p *parser) isWord(text string) bool {
t := p.here()
return t.Kind == Word && !t.Quoted && t.Text == text
}
func (p *parser) isAny(texts ...string) bool {
for _, text := range texts {
if p.isWord(text) {
return true
}
}
return false
}
// list reads commands until one of the words that closes the block it is
// in. The stoppers are passed down rather than hard coded, because done
// ends a loop and fi ends an if and neither of them ends the other.
func (p *parser) list(stop []string) Node {
p.deep++
defer func() { p.deep-- }()
if p.deep > deepest {
p.Gaps = append(p.Gaps, "the script nests deeper than anything this reads")
return &List{}
}
out := &List{}
for {
p.skipNewlines()
if p.done() {
return out
}
for _, word := range stop {
if p.isWord(word) {
return out
}
}
if p.here().Kind == Op && (p.here().Text == ")" || p.here().Text == "}" || p.here().Text == ";;") {
return out
}
before := p.at
node := p.pipeline()
if node == nil {
if p.at == before {
// Nothing was consumed, so take a token to be sure this
// finishes. A script this cannot read is still a script
// that has to be got through.
p.at++
}
continue
}
item := Item{Node: node}
if p.here().Kind == Op {
switch p.here().Text {
case "&&", "||", ";", "&":
item.After = p.next().Text
}
}
out.Items = append(out.Items, item)
}
}
func (p *parser) pipeline() Node {
line := p.here().Line
first := p.command()
if first == nil {
return nil
}
pipe := &Pipeline{Cmds: []Node{first}, Line: line}
for p.here().Kind == Op && (p.here().Text == "|" || p.here().Text == "|&") {
p.next()
p.skipNewlines()
next := p.command()
if next == nil {
break
}
pipe.Cmds = append(pipe.Cmds, next)
}
if len(pipe.Cmds) == 1 {
return pipe.Cmds[0]
}
return pipe
}
func (p *parser) command() Node {
p.skipNewlines()
if p.done() {
return nil
}
switch {
case p.isWord("if"):
return p.ifCommand()
case p.isWord("for"):
return p.forCommand()
case p.isWord("while"), p.isWord("until"):
return p.whileCommand()
case p.isWord("case"):
return p.caseCommand()
case p.isWord("function"):
return p.functionCommand()
}
line := p.here().Line
if p.here().Kind == Op && p.here().Text == "(" {
p.next()
body := p.list(nil)
p.expectOp(")")
return p.trailing(&Subshell{Body: body}, line)
}
if p.isWord("{") {
p.next()
body := p.list([]string{"}"})
p.expectWord("}")
return p.trailing(&Group{Body: body}, line)
}
// A function written the other way: name() { ... }
if p.here().Kind == Word && p.at+1 < len(p.tokens) {
after := p.tokens[p.at+1]
if after.Kind == Op && after.Text == "(" && p.at+2 < len(p.tokens) {
closing := p.tokens[p.at+2]
if closing.Kind == Op && closing.Text == ")" {
name := p.next().Text
p.next()
p.next()
p.skipNewlines()
body := p.command()
return &Func{Name: name, Body: body, Line: after.Line}
}
}
}
return p.simple()
}
// simple reads one plain command: the assignments in front of it, the
// words, and the redirections, in whatever order the redirections were
// written, because a redirect can sit anywhere.
func (p *parser) simple() Node {
cmd := &Cmd{Line: p.here().Line}
for {
t := p.here()
switch {
case t.Kind == Word:
if len(cmd.Words) == 0 {
if name, value, ok := assignment(t); ok {
p.next()
cmd.Assigns = append(cmd.Assigns, Assign{Name: name, Value: value, Line: t.Line})
continue
}
}
p.next()
cmd.Words = append(cmd.Words, t)
case t.Kind == Op && isRedirect(t.Text):
p.next()
r := Redirect{Op: t.Text, Heredoc: t.Heredoc, Frozen: t.Quoted}
if p.here().Kind == Word {
r.Target = p.next()
}
cmd.Redirects = append(cmd.Redirects, r)
default:
if len(cmd.Words) == 0 && len(cmd.Assigns) == 0 && len(cmd.Redirects) == 0 {
return nil
}
return cmd
}
}
}
func isRedirect(op string) bool {
switch op {
case ">", ">>", "<", "2>", "2>>", "&>", "&>>", "<<", "<<-", "<<<", ">|", "<>":
return true
}
return false
}
// assignment recognises NAME=value in front of a command. Only a bare name
// counts: a word with quotes round the name is an argument that happens to
// have an equals sign in it, which is most of the arguments in the world.
func assignment(t Token) (string, Token, bool) {
if len(t.Pieces) == 0 {
return "", Token{}, false
}
first := t.Pieces[0]
if first.Kind != Literal || first.Quote != 0 {
return "", Token{}, false
}
at := -1
for i := 0; i < len(first.Text); i++ {
c := first.Text[i]
if c == '=' {
at = i
break
}
if i == 0 && !isNameStart(c) || !isNameByte(c) {
return "", Token{}, false
}
}
if at <= 0 {
return "", Token{}, false
}
value := Token{Kind: Word, Line: t.Line, Quoted: t.Quoted}
rest := first.Text[at+1:]
if rest != "" {
value.Pieces = append(value.Pieces, Piece{Kind: Literal, Text: rest})
}
value.Pieces = append(value.Pieces, t.Pieces[1:]...)
for _, piece := range value.Pieces {
value.Text += piece.Text
}
return first.Text[:at], value, true
}
func (p *parser) ifCommand() Node {
line := p.next().Line // if
node := &If{Line: line}
node.Cond = p.list([]string{"then", "fi"})
if !p.expectWord("then") {
return node
}
node.Then = p.list([]string{"elif", "else", "fi"})
switch {
case p.isWord("elif"):
// An elif is an if in the else branch, which is what the shell
// does with it too.
node.Else = p.ifTail()
return node
case p.isWord("else"):
p.next()
node.Else = p.list([]string{"fi"})
}
p.expectWord("fi")
return node
}
// ifTail handles elif without needing a keyword of its own.
func (p *parser) ifTail() Node {
line := p.next().Line // elif
node := &If{Line: line}
node.Cond = p.list([]string{"then", "fi"})
if !p.expectWord("then") {
return node
}
node.Then = p.list([]string{"elif", "else", "fi"})
switch {
case p.isWord("elif"):
node.Else = p.ifTail()
return node
case p.isWord("else"):
p.next()
node.Else = p.list([]string{"fi"})
}
p.expectWord("fi")
return node
}
func (p *parser) forCommand() Node {
line := p.next().Line // for
node := &Loop{Line: line}
if p.here().Kind == Word {
node.Name = p.next().Text
}
if p.isWord("in") {
p.next()
for p.here().Kind == Word {
node.In = append(node.In, p.next())
}
}
p.skipNewlines()
if !p.expectWord("do") {
return node
}
node.Body = p.list([]string{"done"})
p.expectWord("done")
return node
}
func (p *parser) whileCommand() Node {
t := p.next() // while or until
node := &Loop{Line: t.Line, Until: t.Text == "until"}
node.Cond = p.list([]string{"do", "done"})
if !p.expectWord("do") {
return node
}
node.Body = p.list([]string{"done"})
p.expectWord("done")
return node
}
func (p *parser) caseCommand() Node {
line := p.next().Line // case
node := &Case{Line: line}
if p.here().Kind == Word {
node.Word = p.next()
}
p.skipNewlines()
if !p.expectWord("in") {
return node
}
for {
p.skipNewlines()
if p.done() || p.isWord("esac") {
break
}
clause := Clause{}
if p.here().Kind == Op && p.here().Text == "(" {
p.next()
}
for p.here().Kind == Word {
clause.Patterns = append(clause.Patterns, p.next())
if p.here().Kind == Op && p.here().Text == "|" {
p.next()
continue
}
break
}
if !p.expectOp(")") {
break
}
clause.Body = p.list([]string{"esac"})
node.Clauses = append(node.Clauses, clause)
if p.here().Kind == Op && p.here().Text == ";;" {
p.next()
}
}
p.expectWord("esac")
return node
}
func (p *parser) functionCommand() Node {
line := p.next().Line // function
node := &Func{Line: line}
if p.here().Kind == Word {
node.Name = p.next().Text
}
if p.here().Kind == Op && p.here().Text == "(" {
p.next()
p.expectOp(")")
}
p.skipNewlines()
node.Body = p.command()
return node
}
func (p *parser) expectWord(text string) bool {
p.skipNewlines()
if p.isWord(text) {
p.next()
return true
}
p.Gaps = append(p.Gaps, "the script does not close a block that was opened, so part of it was read as flat")
return false
}
func (p *parser) expectOp(text string) bool {
p.skipNewlines()
if p.here().Kind == Op && p.here().Text == text {
p.next()
return true
}
p.Gaps = append(p.Gaps, "the script does not close a block that was opened, so part of it was read as flat")
return false
}
// Redirected is a compound command with a redirection hanging off the end
// of it, which is how a script writes several lines into one file:
//
// {
// echo '# bun'
// echo 'export PATH=...'
// } >> "$config"
//
// Reading the block and dropping the redirect loses the only part that
// matters, which is where those lines land. bun's installer writes to
// three different shell profiles this way and nothing else.
type Redirected struct {
Body Node
Redirects []Redirect
Line int
}
func (*Redirected) node() {}
// trailing collects the redirections written after a compound command and
// wraps it in them.
func (p *parser) trailing(body Node, line int) Node {
var found []Redirect
for p.here().Kind == Op && isRedirect(p.here().Text) {
t := p.next()
r := Redirect{Op: t.Text, Heredoc: t.Heredoc, Frozen: t.Quoted}
if p.here().Kind == Word {
r.Target = p.next()
}
found = append(found, r)
}
if len(found) == 0 {
return body
}
return &Redirected{Body: body, Redirects: found, Line: line}
}