/
lexer.go
532 lines (475 loc) · 9.38 KB
/
lexer.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
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
package main
import (
"bytes"
"errors"
"os"
"unicode/utf8"
"github.com/danwakefield/gosh/char"
"github.com/danwakefield/kisslog"
)
const (
EOFRune rune = -1
SentinalEscape rune = 201
SentinalSubstitution rune = 202
)
var (
ErrQuotedString = errors.New("Unterminated quoted string")
)
type LexItem struct {
Tok Token
Pos int
LineNo int
Val string `json:",omitempty"`
Quoted bool
Subs []Substitution `json:",omitempty"`
}
type Lexer struct {
position int
lastPosition int
inputLength int
lineNo int
buffer bytes.Buffer
subs []Substitution
quoted bool
backslash bool
backupWidth int
input string
log *kisslog.Logger
IgnoreNewlines bool
CheckAlias bool
CheckKeyword bool
}
func NewLexer(input string) *Lexer {
l := &Lexer{
input: input,
inputLength: len(input),
subs: []Substitution{},
lineNo: 1,
log: kisslog.New("Lexer"),
IgnoreNewlines: false,
CheckAlias: true,
CheckKeyword: true,
}
return l
}
func (l *Lexer) Next() (li LexItem) {
defer func() {
l.CheckAlias = false
l.IgnoreNewlines = false
l.CheckKeyword = false
}()
li = l.nextLexItem()
for li.Tok == TNewLine && l.IgnoreNewlines {
li = l.nextLexItem()
}
if li.Tok != TWord || li.Quoted {
return li
}
// Check if words are keywords. E.g for
// CheckKeyword flag disables as `for for in 1 2 3`
// is valid
if t, found := KeywordLookup[li.Val]; found && l.CheckKeyword {
return LexItem{
Tok: t,
Pos: li.Pos,
LineNo: li.LineNo,
Val: li.Val,
}
}
if l.CheckAlias {
}
return li
}
func (l *Lexer) nextLexItem() LexItem {
t := l.Start()
li := LexItem{
Tok: t,
Pos: l.lastPosition,
LineNo: l.lineNo,
Val: l.buffer.String(),
Quoted: l.quoted,
Subs: l.subs,
}
l.lastPosition = l.position
l.quoted = false
l.subs = []Substitution{}
l.buffer.Reset()
return li
}
func (l *Lexer) nextChar() rune {
if l.position >= l.inputLength {
l.position++
return EOFRune
}
var (
r rune
w int
)
for {
r, w = utf8.DecodeRuneInString(l.input[l.position:])
l.position += w
l.backupWidth = w
if r != '\x01' {
break
}
}
return r
}
func (l *Lexer) ignore() {
l.lastPosition = l.position
}
func (l *Lexer) backup() {
l.position -= l.backupWidth
l.backupWidth = 0
}
func (l *Lexer) hasNext(r rune) bool {
if r == l.nextChar() {
return true
}
l.backup()
return false
}
func (l *Lexer) Start() Token {
for {
c := l.nextChar()
switch c {
default:
l.backup()
return l.Word()
case EOFRune:
return TEOF
case ' ', '\t':
// Ignore whitespace
l.ignore()
case '#':
// Consume comments upto newline / EOF
for {
c := l.nextChar()
if c == '\n' || c == EOFRune {
l.backup()
l.ignore()
// Break and let the main loop figure out NL vs EOF
break
}
}
case '\\':
// Line continuation or escaped character
if l.hasNext('\n') {
l.lineNo++
continue
}
l.quoted = true
l.backslash = true
return l.Word()
case '\n':
l.lineNo++
return TNewLine
case '&':
if l.hasNext('&') {
return TAnd
} else {
return TBackground
}
case '|':
if l.hasNext('|') {
return TOr
} else {
return TPipe
}
case ';':
if l.hasNext(';') {
return TEndCase
} else {
return TSemicolon
}
case '(':
return TLeftParen
case ')':
return TRightParen
}
}
return TEOF
}
func (l *Lexer) Word() Token {
OuterLoop:
for {
c := l.nextChar()
if l.backslash {
if c == EOFRune {
l.backup()
l.buffer.WriteRune('\\')
break
}
if c == '\\' {
l.buffer.WriteRune('\\')
continue
}
l.buffer.WriteRune(SentinalEscape)
l.buffer.WriteRune(c)
l.backslash = false
continue
}
switch c {
case '\n', '\t', ' ', '<', '>', '(', ')', ';', '&', '|', EOFRune:
// Characters that cause a word break
l.backup()
break OuterLoop
case '\'':
l.quoted = true
l.SingleQuote()
case '"':
l.quoted = true
l.DoubleQuote()
case '`':
l.BackQuote()
case '$':
l.Substitution()
default:
l.buffer.WriteRune(c)
}
}
return TWord
}
func (l *Lexer) DoubleQuote() {
// We have consumed the first quote before entering this state.
for {
c := l.nextChar()
switch c {
case EOFRune:
panic(ErrQuotedString) //TODO: Dont make this panic
case '$':
l.Substitution()
case '"':
return
case '\\':
c = l.nextChar()
switch c {
case '\n':
// Ignore an escaped literal newline
case '\\', '$', '`', '"':
l.buffer.WriteRune(c)
default:
l.backup()
l.buffer.WriteRune('\\')
}
default:
l.buffer.WriteRune(c)
}
}
}
func (l *Lexer) SingleQuote() {
// We have consumed the first quote before entering this state.
for {
c := l.nextChar()
switch c {
case EOFRune:
panic(ErrQuotedString) //TODO: Dont make this panic
case '\'':
return
default:
l.buffer.WriteRune(c)
}
}
}
func (l *Lexer) Substitution() {
// Upon entering we have only read the '$'
// Perform the lex of a single complete substitution before returning
// control to the calling location
c := l.nextChar()
switch {
default:
l.buffer.WriteRune('$')
l.backup()
case c == '(':
if l.hasNext('(') {
l.Arith()
} else {
l.Subshell()
}
case char.IsFirstInVarName(c), char.IsDigit(c), char.IsSpecial(c):
l.backup()
l.VariableSimple()
case c == '{':
l.VariableComplex()
}
}
func (l *Lexer) VariableSimple() {
// When we enter this state we know we have at least one readable
// char for the varname. That means that any character not valid
// just terminates the parsing and we dont have to
// worry about the case of an empty varname
l.buffer.WriteRune(SentinalSubstitution)
sv := SubVariable{SubType: VarSubNormal}
varbuf := bytes.Buffer{}
c := l.nextChar()
switch {
case char.IsSpecial(c):
varbuf.WriteRune(c)
case char.IsDigit(c):
// Positional argv
for {
varbuf.WriteRune(c)
c = l.nextChar()
if !char.IsDigit(c) {
l.backup()
break
}
}
case char.IsFirstInVarName(c):
for {
varbuf.WriteRune(c)
c = l.nextChar()
if !char.IsInVarName(c) {
l.backup()
break
}
}
default:
l.backup()
}
sv.VarName = varbuf.String()
l.subs = append(l.subs, sv)
return
}
func (l *Lexer) VariableComplex() {
// Upon entering we have read the opening '{'
l.buffer.WriteRune(SentinalSubstitution)
sv := SubVariable{}
varbuf := bytes.Buffer{}
defer func() {
// We defer this as there are multiple return points
sv.VarName = varbuf.String()
l.subs = append(l.subs, sv)
}()
if l.hasNext('#') {
// The NParam Special Var
if l.hasNext('}') {
varbuf.WriteRune('#')
return
}
// Length variable operator
sv.SubType = VarSubLength
}
c := l.nextChar()
switch {
case char.IsSpecial(c):
varbuf.WriteRune(c)
case char.IsDigit(c):
for {
varbuf.WriteRune(c)
c = l.nextChar()
if !char.IsDigit(c) {
l.backup()
break
}
}
case char.IsFirstInVarName(c):
for {
varbuf.WriteRune(c)
c = l.nextChar()
if !char.IsInVarName(c) {
l.backup()
break
}
}
case c == EOFRune:
l.backup()
return
}
// Either a Enclosed variable '${foo}' or a length operation '${#foo}'
if l.hasNext('}') {
return
}
// Length operator should have returned since only ${#varname} is valid
if sv.SubType == VarSubLength {
l.log.Error("Line %d: Bad substitution (%s)", l.lineNo, l.input[l.lastPosition:l.position])
os.Exit(1)
}
if l.hasNext(':') {
sv.CheckNull = true
}
switch l.nextChar() {
case '-':
sv.SubType = VarSubMinus
case '+':
sv.SubType = VarSubPlus
case '?':
sv.SubType = VarSubQuestion
case '=':
sv.SubType = VarSubAssign
case '#':
if l.hasNext('#') {
sv.SubType = VarSubTrimLeftMax
} else {
sv.SubType = VarSubTrimLeft
}
case '%':
if l.hasNext('%') {
sv.SubType = VarSubTrimRightMax
} else {
sv.SubType = VarSubTrimRight
}
default:
l.log.Error("Line %d: Bad substitution (%s)", l.lineNo, l.input[l.lastPosition:l.position])
os.Exit(1)
}
// Read until '}'
// In the future to support Nested vars etc create new sublexer from
// l.input[l.pos:] and take the first lexitem as the sub val then adjust
// this lexer's position and trash sublexer
c = l.nextChar()
subValBuf := bytes.Buffer{}
for {
if c == '}' {
break
}
subValBuf.WriteRune(c)
c = l.nextChar()
}
sv.SubVal = subValBuf.String()
}
func (l *Lexer) BackQuote() {
l.log.Error("lexBackQuote - Not Implemented")
os.Exit(2)
}
func (l *Lexer) Subshell() {
l.ignore()
p := NewParser(l.input[l.position:])
ss := SubSubshell{}
ss.N = p.list(AllowEmptyNode)
// We have to explictitly get the next item to prevent race conditions
// in accessing the lexers Pos and LineNo fields.
x := p.lexer.nextLexItem()
l.position += x.Pos
l.lineNo += x.LineNo
l.buffer.WriteRune(SentinalSubstitution)
l.subs = append(l.subs, ss)
return
}
func (l *Lexer) Arith() {
// Upon entering this state we have read the '$(('
l.buffer.WriteRune(SentinalSubstitution)
arithBuf := bytes.Buffer{}
sa := SubArith{}
parenCount := 0
for {
c := l.nextChar()
if parenCount == 0 && c == ')' {
if l.hasNext(')') {
break
}
// Bash just ignores a closing brakcet with no opening
// bracket so we will emulate that.
continue
}
if c == '(' {
parenCount++
}
if c == ')' {
parenCount--
}
arithBuf.WriteRune(c)
}
sa.Raw = arithBuf.String()
l.subs = append(l.subs, sa)
}