This repository has been archived by the owner on Jul 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.go
491 lines (455 loc) · 11.1 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
package compiler
import (
"fmt"
"os"
"strings"
)
func (k LexicalTokenKind) String() string {
return fmt.Sprintf("LexicalTokenKind(%d)", k)
}
const (
// program name, command, argument, variable
LexicalIdentifier LexicalTokenKind = iota
// ;
LexicalStop
// &
LexicalBackground
// |
LexicalPipeStdout
// >
LexicalFileStdout
// >>
LexicalFileAppendStdout
// 2>
LexicalFileStderr
// 2>>
LexicalFileAppendStderr
// &>
LexicalFileStdoutAndStderr
// &>>
LexicalFileAppendStdoutAndStderr
// 2>&1
LexicalStderrToStdout
// 1>&2
LexicalStdoutToStderr
// <
LexicalRedirectStdin
// <<
LexicalHereDocument
// &&
LexicalAnd
// ||
LexicalOr
)
type (
LexicalToken struct {
Content string
// Index is the position of the token in the text.
// This is not 100% accurate because it doesn't take quotation into account.
// It's good enough for error messages.
// Index is always the position of the first character of the token or within the token (in case of quotation).
Index int
Kind LexicalTokenKind
}
LexicalTokenBuilder struct {
Content strings.Builder
Index int
Kind LexicalTokenKind
}
lexicalQuotation uint8
LexicalTokenKind uint8
)
func (t LexicalToken) String() string {
return fmt.Sprintf("LexicalToken{Content: %q, Index: %d, Kind: %s}", t.Content, t.Index, t.Kind.String())
}
func newLexicalTokenBuilder() LexicalTokenBuilder {
b := LexicalTokenBuilder{}
b.Reset()
return b
}
func (b *LexicalTokenBuilder) SetIndex(i int) {
b.Index = i
}
func (b *LexicalTokenBuilder) SetIndexIfEmpty(i int) {
if b.Index == -1 {
b.Index = i
}
}
func (b *LexicalTokenBuilder) WriteChar(c byte, i int) {
b.Content.WriteByte(c)
if b.Index == -1 {
b.Index = i
}
}
func (b *LexicalTokenBuilder) WriteString(s string, i int) {
b.Content.WriteString(s)
if b.Index == -1 {
b.Index = i
}
}
func (b *LexicalTokenBuilder) WriteRune(r rune, i int) {
b.Content.WriteRune(r)
if b.Index == -1 {
b.Index = i
}
}
func (b *LexicalTokenBuilder) Build() LexicalToken {
t := LexicalToken{
Content: b.Content.String(),
Index: b.Index,
Kind: b.Kind,
}
b.Reset()
return t
}
func (t *LexicalTokenBuilder) Reset() {
t.Content.Reset()
t.Kind = LexicalIdentifier
t.Index = -1
}
func (t *LexicalTokenBuilder) SetKind(kind LexicalTokenKind) {
t.Kind = kind
}
func (t *LexicalTokenBuilder) IsPresent() bool {
return t.Index != -1
}
const (
lexicalQuotationNone lexicalQuotation = iota
lexicalQuotationSingle
lexicalQuotationDouble
)
// LexicalAnalysis performs lexical analysis on the given text and returns a slice of tokens.
// If an error gets returned it will be of type CompilerError.
func LexicalAnalysis(text string, iop *ioProvider) ([]LexicalToken, error) {
texLen := len(text)
tokens := make([]LexicalToken, 0)
quotation := lexicalQuotationNone
tb := newLexicalTokenBuilder()
for i := 0; i < texLen; i++ {
switch c := text[i]; c {
case '\n':
if quotation != lexicalQuotationNone {
return nil, newLexicalError(i, text, "quotation not closed at the end of the line")
}
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
tokens = append(tokens, LexicalToken{Kind: LexicalStop, Index: i})
case '\r':
if quotation != lexicalQuotationNone {
tb.WriteChar(c, i)
}
continue
case ' ', '\t', '\v', '\f', 20:
if quotation == lexicalQuotationNone {
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
} else {
tb.WriteChar(c, i)
}
case '$':
if i+1 < texLen && text[i+1] == '(' {
// subshell
tb.SetIndexIfEmpty(i)
i += 2
var subshell strings.Builder
braceCount := 1
for i < texLen {
c := text[i]
if c == '(' {
braceCount++
} else if c == ')' {
braceCount--
if braceCount == 0 {
break
}
}
subshell.WriteByte(c)
i++
}
iop, sb := subshellIoProvider(iop)
defer iop.Close()
if err := Execute(subshell.String(), iop); err != nil {
return nil, newLexicalError(i, text, fmt.Sprintf("failed to execute subshell: %v", err))
}
tb.WriteString(strings.TrimSpace(sb.String()), i)
} else {
// variable
tb.SetIndexIfEmpty(i)
varName := strings.Builder{}
for i += 1; i < texLen; i++ {
c := text[i]
if c == ' ' || c == ';' || c == '\t' || c == '\v' || c == '\f' || c == '\n' || c == '\r' || c == '.' || c == ',' || c == '/' || c == '>' || c == '<' || c == '&' || c == '|' {
i--
break
}
varName.WriteByte(c)
}
tb.WriteString(os.Getenv(varName.String()), i)
}
case '"':
tb.SetIndexIfEmpty(i)
switch quotation {
case lexicalQuotationNone:
quotation = lexicalQuotationDouble
case lexicalQuotationDouble:
quotation = lexicalQuotationNone
case lexicalQuotationSingle:
tb.WriteChar(c, i)
default:
return nil, newLexicalError(i, text, fmt.Sprintf("invalid quotation state: %d", quotation))
}
case '\'':
tb.SetIndexIfEmpty(i)
switch quotation {
case lexicalQuotationNone:
quotation = lexicalQuotationSingle
case lexicalQuotationSingle:
quotation = lexicalQuotationNone
case lexicalQuotationDouble:
tb.WriteChar(c, i)
default:
return nil, newLexicalError(i, text, fmt.Sprintf("invalid quotation state: %d", quotation))
}
case '\\':
if quotation == lexicalQuotationNone {
if i == texLen-1 {
return nil, newLexicalError(i, text, "iscape character at the end of the text")
}
} else {
if i+1 < texLen {
switch c = text[i+1]; c {
case 'a':
tb.WriteString("\a", i)
case 'b':
tb.WriteString("\b", i)
case '$':
tb.WriteString("$", i)
case 'n', '\n':
tb.WriteString("\n", i)
case 'r', '\r':
tb.WriteString("\r", i)
case 't':
tb.WriteString("\t", i)
case 'v':
tb.WriteString("\v", i)
case 'f':
tb.WriteString("\f", i)
case '\\':
tb.WriteString("\\", i)
case '"':
tb.WriteString("\"", i)
case '\'':
tb.WriteString("'", i)
case '0':
tb.WriteString("\x00", i)
case ';':
tb.WriteString(";", i)
case '&':
tb.WriteString("&", i)
case '|':
tb.WriteString("|", i)
case '>':
tb.WriteString(">", i)
case '<':
tb.WriteString("<", i)
default:
tb.WriteString(fmt.Sprintf("\\%c", c), i)
}
i++
} else {
return nil, newLexicalError(i, text, "escape character at the end of the text")
}
}
case ';':
if quotation == lexicalQuotationNone {
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
tokens = append(tokens, LexicalToken{Kind: LexicalStop, Index: i})
} else {
tb.WriteChar(c, i)
}
case '&':
if quotation == lexicalQuotationNone {
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
if i+1 < texLen && text[i+1] == '&' {
// &&
tokens = append(tokens, LexicalToken{Kind: LexicalAnd, Index: i})
i++
break
} else if i+1 < texLen && text[i+1] == '>' {
if i+2 < texLen && text[i+2] == '>' {
// &>>
tokens = append(tokens, LexicalToken{Kind: LexicalFileAppendStdoutAndStderr, Index: i})
i += 2
break
} else {
// &>
tokens = append(tokens, LexicalToken{Kind: LexicalFileStdoutAndStderr, Index: i})
i++
break
}
} else {
// &
tokens = append(tokens, LexicalToken{Kind: LexicalBackground, Index: i})
break
}
} else {
tb.WriteChar(c, i)
}
case '|':
if quotation == lexicalQuotationNone {
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
if i+1 < texLen && text[i+1] == '|' {
tokens = append(tokens, LexicalToken{Kind: LexicalOr, Index: i})
i++
break
} else {
// |
tokens = append(tokens, LexicalToken{Kind: LexicalPipeStdout, Index: i})
break
}
} else {
tb.WriteChar(c, i)
}
case '>':
if quotation == lexicalQuotationNone {
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
if i+1 < texLen && text[i+1] == '>' {
// >>
tokens = append(tokens, LexicalToken{Kind: LexicalFileAppendStdout, Index: i})
i++
break
} else {
// >
tokens = append(tokens, LexicalToken{Kind: LexicalFileStdout, Index: i})
break
}
}
tb.WriteChar(c, i)
case '<':
if quotation == lexicalQuotationNone {
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
if i+1 < texLen && text[i+1] == '<' {
// <<
tb.SetIndexIfEmpty(i)
tb.SetKind(LexicalHereDocument)
// get the here document name
docNameB := strings.Builder{}
for i += 2; i < texLen; i++ {
c := text[i]
if c == '\n' {
break
}
docNameB.WriteByte(c)
}
docName := strings.TrimSpace(docNameB.String())
// get the here document content
err := func() error {
var lineContentBuilder strings.Builder
for i += 1; i < texLen; i++ {
switch c := text[i]; c {
case '\n':
lineContent := lineContentBuilder.String()
if strings.TrimSpace(lineContent) == docName {
i--
return nil
} else {
lineContentBuilder.Reset()
tb.WriteString(lineContent, i)
tb.WriteRune('\n', i)
}
case '\r':
continue
default:
lineContentBuilder.WriteByte(c)
}
}
lineContent := lineContentBuilder.String()
if strings.TrimSpace(lineContent) == docName {
return nil
}
return newLexicalError(tb.Index, text, "here document not closed")
}()
if err != nil {
return nil, err
}
t := tb.Build()
t.Content = strings.Trim(t.Content, "\n") + "\n"
tokens = append(tokens, t)
break
} else {
// <
tokens = append(tokens, LexicalToken{Kind: LexicalRedirectStdin, Index: i})
break
}
}
tb.WriteChar(c, i)
case '1':
if tb.IsPresent() {
tb.WriteChar(c, i)
break
}
if i+1 < texLen && text[i+1] == '>' {
if i+2 < texLen && text[i+2] == '&' {
if i+3 < texLen && text[i+3] == '2' {
// 1>&2
tokens = append(tokens, LexicalToken{Kind: LexicalStdoutToStderr, Index: i})
i += 3
break
}
}
}
tb.WriteChar(c, i)
case '2':
if tb.IsPresent() {
tb.WriteChar(c, i)
break
}
if i+1 < texLen && text[i+1] == '>' {
if i+2 < texLen && text[i+2] == '&' {
if i+3 < texLen && text[i+3] == '1' {
// 2>&1
tokens = append(tokens, LexicalToken{Kind: LexicalStderrToStdout, Index: i})
i += 3
break
}
} else if i+2 < texLen && text[i+2] == '>' {
// 2>>
tokens = append(tokens, LexicalToken{Kind: LexicalFileAppendStderr, Index: i})
i += 2
break
} else {
// 2>
tokens = append(tokens, LexicalToken{Kind: LexicalFileStderr, Index: i})
i++
break
}
}
tb.WriteChar(c, i)
default:
tb.WriteChar(c, i)
}
}
if quotation != lexicalQuotationNone {
return nil, newLexicalError(len(text)-1, text, "quotation not closed")
}
if tb.IsPresent() {
tokens = append(tokens, tb.Build())
}
// trim trailing LexicalStop tokens
for len(tokens) > 0 && tokens[len(tokens)-1].Kind == LexicalStop {
tokens = tokens[:len(tokens)-1]
}
return tokens, nil
}