Repository navigation
Expand file tree
/
Copy pathlex.go
More file actions
668 lines (631 loc) · 17.2 KB
/
Copy pathlex.go
File metadata and controls
668 lines (631 loc) · 17.2 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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
package main
// Taking a shell script apart into words.
//
// This is the part everything else stands on, so it is worth saying what a
// word is, because it is not what it looks like. In a shell,
// curl "$BASE/install.sh" is one word made of four pieces: a literal, a
// variable, a literal, and the end. Whether that word turns out to be a URL
// somebody is about to pipe into a shell depends on the value of BASE, and
// the only way to answer that is to keep the pieces apart until something
// later can put them together.
//
// So nothing here throws away structure. Quoting is recorded rather than
// resolved, because 'single' and "double" behave differently and the
// difference is the whole game: $HOME inside single quotes is four
// characters and inside double quotes it is a home directory. A word that
// came out of a command substitution is marked as such, because its value
// is unknowable here and pretending otherwise is how a reader gets confident
// about the wrong thing.
import (
"strings"
)
type TokenKind int
const (
// Word is anything that is not an operator: a command name, an
// argument, an assignment, a filename after a redirect.
Word TokenKind = iota
// Op is one of the punctuation marks that join words into something
// bigger: the pipe, the semicolon, the ampersands.
Op
// Newline ends a command, and unlike a semicolon it can be swallowed
// after some operators, which is why it is its own thing.
Newline
// End is the end of the input.
End
)
// PieceKind is what one part of a word is made of.
type PieceKind int
const (
// Literal is text that means itself.
Literal PieceKind = iota
// Variable is $NAME or ${NAME} or ${NAME:-something}.
Variable
// Command is $(...) or `...`, whose value cannot be known here.
Command
// Arithmetic is $((...)), same problem and a favourite of anybody
// building a string out of numbers to keep it off the screen.
Arithmetic
)
// Piece is one part of a word, with the quoting it was written under.
type Piece struct {
Kind PieceKind
Text string
// Inside is the script inside a $( ), kept so it can be read on its
// own: a command substitution is a whole script and the interesting
// thing is often in there rather than around it.
Inside string
// Or is the value after :- or :=, the one used when the variable is
// not set. Kept because it is almost always the answer: ${ZDOTDIR:-$HOME}
// is a home directory on every machine where nobody set ZDOTDIR, which
// is most of them, and dropping it turns ~/.zshrc into $ZDOTDIR/.zshrc
// and loses the finding.
Or string
// Quote is 0 for bare, '\'' for single, '"' for double, and '$' for
// the $'...' form, which is the one that turns \x63 into a c and is
// therefore the one worth knowing about.
Quote byte
}
type Token struct {
Kind TokenKind
Text string
Pieces []Piece
Line int
// Heredoc is the body of a here-document attached to this operator,
// filled in once the body has been read off the following lines.
Heredoc string
// Quoted says a word had quotes anywhere in it, which decides whether
// it could have been split into several words at runtime.
Quoted bool
}
// operators, longest first, because << has to win over < and &&> would
// otherwise be read as & followed by &>.
var operators = []string{
"<<<", "&>>", "2>>", "<<-", "&&", "||", ";;", "<<", ">>", "&>", "2>",
">|", "<>", "|&", "|", ";", "&", "(", ")", "<", ">",
}
type lexer struct {
src string
at int
line int
// pending are here-doc operators waiting for their body, which starts
// on the line after the one the operator is on.
pending []*Token
out []Token
// Gaps is anything that could not be read: an unterminated quote, a
// here-doc with no end. They are reported rather than swallowed.
Gaps []string
}
func lex(src string) ([]Token, []string) {
l := &lexer{src: src, line: 1}
l.run()
l.out = append(l.out, Token{Kind: End, Line: l.line})
return l.out, l.Gaps
}
func (l *lexer) run() {
for {
l.skipBlanks()
if l.at >= len(l.src) {
return
}
c := l.src[l.at]
switch {
case c == '#':
for l.at < len(l.src) && l.src[l.at] != '\n' {
l.at++
}
case c == '\n':
l.at++
l.emit(Token{Kind: Newline, Text: "\n", Line: l.line})
l.line++
l.readHeredocs()
default:
if op, found := l.operatorAt(); found {
l.at += len(op)
token := Token{Kind: Op, Text: op, Line: l.line}
l.emit(token)
if op == "<<" || op == "<<-" {
l.pending = append(l.pending, &l.out[len(l.out)-1])
}
continue
}
l.readWord()
}
}
}
func (l *lexer) emit(t Token) { l.out = append(l.out, t) }
func (l *lexer) operatorAt() (string, bool) {
rest := l.src[l.at:]
// Process substitution is not a redirect. <(...) and >(...) sit where
// a word goes, and reading the angle bracket as an operator here is
// what turns "bash <(curl ...)" into a redirect from a subshell and
// loses the fact that the shell is being handed a downloaded script.
if strings.HasPrefix(rest, "<(") || strings.HasPrefix(rest, ">(") {
return "", false
}
for _, op := range operators {
if strings.HasPrefix(rest, op) {
return op, true
}
}
return "", false
}
func (l *lexer) skipBlanks() {
for l.at < len(l.src) {
c := l.src[l.at]
if c == ' ' || c == '\t' || c == '\r' {
l.at++
continue
}
// A backslash at the end of a line joins the two lines, and it is
// how a one line installer gets written as forty readable ones.
if c == '\\' && l.at+1 < len(l.src) && l.src[l.at+1] == '\n' {
l.at += 2
l.line++
continue
}
return
}
}
// readWord reads until something that ends a word, keeping the pieces.
func (l *lexer) readWord() {
start := l.at
token := Token{Kind: Word, Line: l.line}
var plain strings.Builder
for l.at < len(l.src) {
c := l.src[l.at]
if c == ' ' || c == '\t' || c == '\r' || c == '\n' {
break
}
if c == '\\' && l.at+1 < len(l.src) && l.src[l.at+1] == '\n' {
l.at += 2
l.line++
continue
}
if _, isOp := l.operatorAt(); isOp && c != '$' {
break
}
switch c {
case '\'':
token.Quoted = true
text, ok := l.readSingle()
if !ok {
l.Gaps = append(l.Gaps, "a quote is never closed")
}
token.Pieces = append(token.Pieces, Piece{Kind: Literal, Text: text, Quote: '\''})
plain.WriteString(text)
case '"':
token.Quoted = true
pieces, ok := l.readDouble()
if !ok {
l.Gaps = append(l.Gaps, "a quote is never closed")
}
token.Pieces = append(token.Pieces, pieces...)
for _, p := range pieces {
plain.WriteString(p.Text)
}
case '$':
if piece, ok := l.readDollar(); ok {
if piece.Quote == '$' {
token.Quoted = true
}
token.Pieces = append(token.Pieces, piece)
plain.WriteString(piece.Text)
continue
}
l.at++
token.Pieces = append(token.Pieces, Piece{Kind: Literal, Text: "$"})
plain.WriteString("$")
case '`':
inside, ok := l.readBackticks()
if !ok {
l.Gaps = append(l.Gaps, "a backtick is never closed")
}
token.Pieces = append(token.Pieces, Piece{Kind: Command, Inside: inside})
case '\\':
l.at++
if l.at < len(l.src) {
token.Pieces = append(token.Pieces, Piece{Kind: Literal, Text: string(l.src[l.at])})
plain.WriteByte(l.src[l.at])
l.at++
}
default:
// Process substitution, bash's <( ) and >( ), which is how
// "bash <(curl ...)" is written. It sits where a word goes
// rather than where a redirect goes, so it is read here and
// not with the operators, and what is inside it is a script
// of its own.
if strings.HasPrefix(l.src[l.at:], "<(") || strings.HasPrefix(l.src[l.at:], ">(") {
lead := l.src[l.at : l.at+2]
inside, ok := l.readNested(lead, "(", ")")
if !ok {
l.Gaps = append(l.Gaps, "a process substitution is never closed")
}
token.Pieces = append(token.Pieces, Piece{Kind: Command, Inside: inside})
continue
}
from := l.at
for l.at < len(l.src) && !strings.ContainsRune(" \t\r\n'\"$`\\", rune(l.src[l.at])) {
if _, isOp := l.operatorAt(); isOp {
break
}
l.at++
}
if l.at == from {
l.at++
}
text := l.src[from:l.at]
token.Pieces = append(token.Pieces, Piece{Kind: Literal, Text: text})
plain.WriteString(text)
}
}
if l.at == start {
// Nothing was consumed, which would loop forever. Take one byte
// and carry on: a script this program cannot read is still a
// script it has to finish reading.
l.at++
return
}
token.Text = plain.String()
l.emit(token)
}
func (l *lexer) readSingle() (string, bool) {
l.at++ // the opening quote
from := l.at
for l.at < len(l.src) {
if l.src[l.at] == '\'' {
text := l.src[from:l.at]
l.at++
l.line += strings.Count(text, "\n")
return text, true
}
l.at++
}
return l.src[from:], false
}
// readDouble keeps the pieces, because inside double quotes a variable is
// still a variable and a command substitution is still a command.
func (l *lexer) readDouble() ([]Piece, bool) {
l.at++ // the opening quote
var out []Piece
var plain strings.Builder
flush := func() {
if plain.Len() > 0 {
out = append(out, Piece{Kind: Literal, Text: plain.String(), Quote: '"'})
plain.Reset()
}
}
for l.at < len(l.src) {
c := l.src[l.at]
switch c {
case '"':
l.at++
flush()
return out, true
case '\\':
l.at++
if l.at < len(l.src) {
// Inside double quotes a backslash only escapes a handful
// of characters and is literal before anything else.
next := l.src[l.at]
if !strings.ContainsRune("$`\"\\\n", rune(next)) {
plain.WriteByte('\\')
}
if next == '\n' {
l.line++
} else {
plain.WriteByte(next)
}
l.at++
}
case '$':
if piece, ok := l.readDollar(); ok {
flush()
piece.Quote = '"'
out = append(out, piece)
continue
}
plain.WriteByte('$')
l.at++
case '`':
flush()
inside, ok := l.readBackticks()
out = append(out, Piece{Kind: Command, Inside: inside, Quote: '"'})
if !ok {
return out, false
}
default:
if c == '\n' {
l.line++
}
plain.WriteByte(c)
l.at++
}
}
flush()
return out, false
}
// readDollar reads whatever kind of expansion this is. It is called with
// the cursor on the dollar.
func (l *lexer) readDollar() (Piece, bool) {
rest := l.src[l.at:]
switch {
case strings.HasPrefix(rest, "$(("):
inside, ok := l.readNested("$((", "((", "))")
return Piece{Kind: Arithmetic, Inside: inside}, ok
case strings.HasPrefix(rest, "$("):
inside, ok := l.readNested("$(", "(", ")")
return Piece{Kind: Command, Inside: inside}, ok
case strings.HasPrefix(rest, "${"):
return l.readBraced()
case strings.HasPrefix(rest, "$'"):
l.at++ // the dollar
text, ok := l.readSingle()
// This is the form that turns \x63\x75\x72\x6c into curl, so it
// gets unescaped here and marked, and the marking is what lets a
// finding say the word was written in escapes.
return Piece{Kind: Literal, Text: unescapeAnsiC(text), Quote: '$'}, ok
case strings.HasPrefix(rest, `$"`):
l.at++
pieces, ok := l.readDouble()
text := ""
for _, p := range pieces {
text += p.Text
}
return Piece{Kind: Literal, Text: text, Quote: '"'}, ok
}
// A bare $NAME, or one of the special ones like $?, $1, $@.
if len(rest) < 2 {
return Piece{}, false
}
l.at++
c := l.src[l.at]
if isNameStart(c) {
from := l.at
for l.at < len(l.src) && isNameByte(l.src[l.at]) {
l.at++
}
return Piece{Kind: Variable, Text: l.src[from:l.at]}, true
}
if strings.IndexByte("?$!#*@0123456789-", c) >= 0 {
l.at++
return Piece{Kind: Variable, Text: string(c)}, true
}
l.at--
return Piece{}, false
}
// readBraced reads ${NAME}, and the forms with a modifier on the end. The
// name is what matters; the modifier is kept in the text of the piece so a
// reader can tell ${TOKEN} from ${TOKEN:-nothing}.
func (l *lexer) readBraced() (Piece, bool) {
inside, ok := l.readNested("${", "{", "}")
if !ok {
return Piece{Kind: Variable, Text: inside}, false
}
name := inside
// ${!name} is the indirect form: it uses the value of one variable as
// the name of another, which is a way of writing a name that is not in
// the file. Worth keeping whole so it can be pointed at.
if strings.HasPrefix(name, "!") {
return Piece{Kind: Variable, Text: name}, true
}
or := ""
if at := strings.IndexAny(name, ":-+=?#%/^,"); at > 0 {
rest := name[at:]
name = name[:at]
for _, mark := range []string{":-", ":=", "-", "="} {
if value, found := strings.CutPrefix(rest, mark); found {
or = value
break
}
}
}
if strings.HasPrefix(inside, "#") && len(inside) > 1 {
name = strings.TrimPrefix(inside, "#")
or = ""
}
return Piece{Kind: Variable, Text: name, Or: or}, true
}
// readNested reads a bracketed run, counting the brackets so that a $( )
// with another $( ) inside it comes out whole.
func (l *lexer) readNested(prefix, open, close string) (string, bool) {
l.at += len(prefix)
from := l.at
depth := 1
for l.at < len(l.src) {
switch {
case strings.HasPrefix(l.src[l.at:], close):
depth--
if depth == 0 {
inside := l.src[from:l.at]
l.at += len(close)
l.line += strings.Count(inside, "\n")
return inside, true
}
l.at += len(close)
case strings.HasPrefix(l.src[l.at:], open):
depth++
l.at += len(open)
case l.src[l.at] == '\'':
l.readSingle()
default:
l.at++
}
}
return l.src[from:], false
}
func (l *lexer) readBackticks() (string, bool) {
l.at++
from := l.at
for l.at < len(l.src) {
if l.src[l.at] == '\\' {
l.at += 2
continue
}
if l.src[l.at] == '`' {
inside := l.src[from:l.at]
l.at++
l.line += strings.Count(inside, "\n")
return inside, true
}
l.at++
}
return l.src[from:], false
}
// readHeredocs is called at every newline, because that is where the body
// of a here-document starts. An installer that writes a systemd unit or a
// shell profile does it with one of these, so the body has to be read and
// kept rather than skipped over as noise.
func (l *lexer) readHeredocs() {
for _, op := range l.pending {
// The word after the operator is the delimiter. Quoting it turns
// off expansion inside the body, which matters: an unquoted one
// can carry a token in from a variable.
tag, dash, quoted := l.heredocTag(op)
if tag == "" {
continue
}
var body strings.Builder
for l.at < len(l.src) {
end := strings.IndexByte(l.src[l.at:], '\n')
line := ""
if end < 0 {
line = l.src[l.at:]
l.at = len(l.src)
} else {
line = l.src[l.at : l.at+end]
l.at += end + 1
}
l.line++
check := line
if dash {
check = strings.TrimLeft(line, "\t")
}
if strings.TrimRight(check, "\r") == tag {
op.Heredoc = body.String()
op.Quoted = quoted
break
}
body.WriteString(line)
body.WriteString("\n")
if end < 0 {
op.Heredoc = body.String()
l.Gaps = append(l.Gaps, "a here-document is never closed")
break
}
}
if op.Heredoc == "" {
op.Heredoc = body.String()
}
}
l.pending = nil
}
// heredocTag finds the delimiter that was written after the << operator.
func (l *lexer) heredocTag(op *Token) (tag string, dash, quoted bool) {
dash = op.Text == "<<-"
for i := range l.out {
if &l.out[i] != op {
continue
}
if i+1 < len(l.out) && l.out[i+1].Kind == Word {
next := l.out[i+1]
return next.Text, dash, next.Quoted
}
}
return "", dash, false
}
func isNameStart(c byte) bool {
return c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'
}
func isNameByte(c byte) bool {
return isNameStart(c) || c >= '0' && c <= '9'
}
// unescapeAnsiC turns the escapes of the $'...' form into the bytes they
// stand for. This exists because it is the tidiest way to write a command
// nobody skimming the file will read: $'\x63\x75\x72\x6c' is curl, and it
// is four characters of intent hidden in twenty of hex.
func unescapeAnsiC(s string) string {
var out strings.Builder
for i := 0; i < len(s); i++ {
if s[i] != '\\' || i+1 >= len(s) {
out.WriteByte(s[i])
continue
}
i++
switch s[i] {
case 'n':
out.WriteByte('\n')
case 't':
out.WriteByte('\t')
case 'r':
out.WriteByte('\r')
case 'a':
out.WriteByte(7)
case 'b':
out.WriteByte(8)
case 'f':
out.WriteByte(12)
case 'v':
out.WriteByte(11)
case 'e', 'E':
out.WriteByte(27)
case '\\', '\'', '"', '?':
out.WriteByte(s[i])
case 'x':
n, used := hexRun(s[i+1:], 2)
if used == 0 {
out.WriteString("\\x")
continue
}
out.WriteByte(byte(n))
i += used
case 'u', 'U':
width := 4
if s[i] == 'U' {
width = 8
}
n, used := hexRun(s[i+1:], width)
if used == 0 {
out.WriteByte(s[i])
continue
}
out.WriteRune(rune(n))
i += used
default:
if s[i] >= '0' && s[i] <= '7' {
n, used := octalRun(s[i:], 3)
out.WriteByte(byte(n))
i += used - 1
continue
}
out.WriteByte('\\')
out.WriteByte(s[i])
}
}
return out.String()
}
func hexRun(s string, most int) (value, used int) {
for used < most && used < len(s) {
c := s[used]
var digit int
switch {
case c >= '0' && c <= '9':
digit = int(c - '0')
case c >= 'a' && c <= 'f':
digit = int(c-'a') + 10
case c >= 'A' && c <= 'F':
digit = int(c-'A') + 10
default:
return value, used
}
value = value*16 + digit
used++
}
return value, used
}
func octalRun(s string, most int) (value, used int) {
for used < most && used < len(s) && s[used] >= '0' && s[used] <= '7' {
value = value*8 + int(s[used]-'0')
used++
}
return value, used
}