/
interp.go
1362 lines (1271 loc) · 33.5 KB
/
interp.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
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package interp is the GoAWK interpreter (a simple tree-walker).
//
// For basic usage, use the Exec function. For more complicated use
// cases and configuration options, first use the parser package to
// parse the AWK source, and then use ExecProgram to execute it with
// a specific configuration.
//
package interp
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"math/rand"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"unicode/utf8"
"github.com/benhoyt/goawk/internal/ast"
. "github.com/benhoyt/goawk/lexer"
"github.com/benhoyt/goawk/parser"
)
var (
errExit = errors.New("exit")
errBreak = errors.New("break")
errContinue = errors.New("continue")
errNext = errors.New("next")
crlfNewline = runtime.GOOS == "windows"
varRegex = regexp.MustCompile(`^([_a-zA-Z][_a-zA-Z0-9]*)=(.*)`)
)
// Error (actually *Error) is returned by Exec and Eval functions on
// interpreter error, for example a negative field index.
type Error struct {
message string
}
func (e *Error) Error() string {
return e.message
}
func newError(format string, args ...interface{}) error {
return &Error{fmt.Sprintf(format, args...)}
}
type returnValue struct {
Value value
}
func (r returnValue) Error() string {
return "<return " + r.Value.str("%.6g") + ">"
}
type interp struct {
// Input/output
output io.Writer
errorOutput io.Writer
scanner *bufio.Scanner
scanners map[string]*bufio.Scanner
stdin io.Reader
filenameIndex int
hadFiles bool
input io.Reader
inputStreams map[string]io.ReadCloser
outputStreams map[string]io.WriteCloser
commands map[string]*exec.Cmd
noExec bool
noFileWrites bool
noFileReads bool
shellCommand []string
// Scalars, arrays, and function state
globals []value
stack []value
frame []value
arrays []map[string]value
localArrays [][]int
callDepth int
nativeFuncs []nativeFunc
// File, line, and field handling
filename value
line string
lineIsTrueStr bool
lineNum int
fileLineNum int
fields []string
fieldsIsTrueStr []bool
numFields int
haveFields bool
// Built-in variables
argc int
convertFormat string
outputFormat string
fieldSep string
fieldSepRegex *regexp.Regexp
recordSep string
recordSepRegex *regexp.Regexp
recordTerminator string
outputFieldSep string
outputRecordSep string
subscriptSep string
matchLength int
matchStart int
// Misc pieces of state
program *parser.Program
random *rand.Rand
randSeed float64
exitStatus int
regexCache map[string]*regexp.Regexp
formatCache map[string]cachedFormat
}
// Various const configuration. Could make these part of Config if
// we wanted to, but no need for now.
const (
maxCachedRegexes = 100
maxCachedFormats = 100
maxRecordLength = 10 * 1024 * 1024 // 10MB seems like plenty
maxFieldIndex = 1000000
maxCallDepth = 1000
initialStackSize = 100
outputBufSize = 64 * 1024
inputBufSize = 64 * 1024
)
// Config defines the interpreter configuration for ExecProgram.
type Config struct {
// Standard input reader (defaults to os.Stdin)
Stdin io.Reader
// Writer for normal output (defaults to a buffered version of
// os.Stdout)
Output io.Writer
// Writer for non-fatal error messages (defaults to os.Stderr)
Error io.Writer
// The name of the executable (accessible via ARGV[0])
Argv0 string
// Input arguments (usually filenames): empty slice means read
// only from Stdin, and a filename of "-" means read from Stdin
// instead of a real file.
Args []string
// List of name-value pairs for variables to set before executing
// the program (useful for setting FS and other built-in
// variables, for example []string{"FS", ",", "OFS", ","}).
Vars []string
// Map of named Go functions to allow calling from AWK. You need
// to pass this same map to the parser.ParseProgram config.
//
// Functions can have any number of parameters, and variadic
// functions are supported. Functions can have no return values,
// one return value, or two return values (result, error). In the
// two-value case, if the function returns a non-nil error,
// program execution will stop and ExecProgram will return that
// error.
//
// Apart from the error return value, the types supported are
// bool, integer and floating point types (excluding complex),
// and string types (string or []byte).
//
// It's not an error to call a Go function from AWK with fewer
// arguments than it has parameters in Go. In this case, the zero
// value will be used for any additional parameters. However, it
// is a parse error to call a non-variadic function from AWK with
// more arguments than it has parameters in Go.
//
// Functions defined with the "function" keyword in AWK code
// take precedence over functions in Funcs.
Funcs map[string]interface{}
// Set one or more of these to true to prevent unsafe behaviours,
// useful when executing untrusted scripts:
//
// * NoExec prevents system calls via system() or pipe operator
// * NoFileWrites prevents writing to files via '>' or '>>'
// * NoFileReads prevents reading from files via getline or the
// filenames in Args
NoExec bool
NoFileWrites bool
NoFileReads bool
// Exec args used to run system shell. Typically, this will
// be {"/bin/sh", "-c"}
ShellCommand []string
// List of name-value pairs to be assigned to the ENVIRON special
// array, for example []string{"USER", "bob", "HOME", "/home/bob"}.
// If nil (the default), values from os.Environ() are used.
Environ []string
}
// ExecProgram executes the parsed program using the given interpreter
// config, returning the exit status code of the program. Error is nil
// on successful execution of the program, even if the program returns
// a non-zero status code.
func ExecProgram(program *parser.Program, config *Config) (int, error) {
if len(config.Vars)%2 != 0 {
return 0, newError("length of config.Vars must be a multiple of 2, not %d", len(config.Vars))
}
if len(config.Environ)%2 != 0 {
return 0, newError("length of config.Environ must be a multiple of 2, not %d", len(config.Environ))
}
p := &interp{program: program}
// Allocate memory for variables
p.globals = make([]value, len(program.Scalars))
p.stack = make([]value, 0, initialStackSize)
p.arrays = make([]map[string]value, len(program.Arrays), len(program.Arrays)+initialStackSize)
for i := 0; i < len(program.Arrays); i++ {
p.arrays[i] = make(map[string]value)
}
// Initialize defaults
p.regexCache = make(map[string]*regexp.Regexp, 10)
p.formatCache = make(map[string]cachedFormat, 10)
p.randSeed = 1.0
seed := math.Float64bits(p.randSeed)
p.random = rand.New(rand.NewSource(int64(seed)))
p.convertFormat = "%.6g"
p.outputFormat = "%.6g"
p.fieldSep = " "
p.recordSep = "\n"
p.outputFieldSep = " "
p.outputRecordSep = "\n"
p.subscriptSep = "\x1c"
p.noExec = config.NoExec
p.noFileWrites = config.NoFileWrites
p.noFileReads = config.NoFileReads
err := p.initNativeFuncs(config.Funcs)
if err != nil {
return 0, err
}
// Setup ARGV and other variables from config
argvIndex := program.Arrays["ARGV"]
p.setArrayValue(ast.ScopeGlobal, argvIndex, "0", str(config.Argv0))
p.argc = len(config.Args) + 1
for i, arg := range config.Args {
p.setArrayValue(ast.ScopeGlobal, argvIndex, strconv.Itoa(i+1), numStr(arg))
}
p.filenameIndex = 1
p.hadFiles = false
for i := 0; i < len(config.Vars); i += 2 {
err := p.setVarByName(config.Vars[i], config.Vars[i+1])
if err != nil {
return 0, err
}
}
// Setup ENVIRON from config or environment variables
environIndex := program.Arrays["ENVIRON"]
if config.Environ != nil {
for i := 0; i < len(config.Environ); i += 2 {
p.setArrayValue(ast.ScopeGlobal, environIndex, config.Environ[i], numStr(config.Environ[i+1]))
}
} else {
for _, kv := range os.Environ() {
eq := strings.IndexByte(kv, '=')
if eq >= 0 {
p.setArrayValue(ast.ScopeGlobal, environIndex, kv[:eq], numStr(kv[eq+1:]))
}
}
}
// Setup system shell command
if len(config.ShellCommand) != 0 {
p.shellCommand = config.ShellCommand
} else {
executable := "/bin/sh"
if runtime.GOOS == "windows" {
executable = "sh"
}
p.shellCommand = []string{executable, "-c"}
}
// Setup I/O structures
p.stdin = config.Stdin
if p.stdin == nil {
p.stdin = os.Stdin
}
p.output = config.Output
if p.output == nil {
p.output = bufio.NewWriterSize(os.Stdout, outputBufSize)
}
p.errorOutput = config.Error
if p.errorOutput == nil {
p.errorOutput = os.Stderr
}
p.inputStreams = make(map[string]io.ReadCloser)
p.outputStreams = make(map[string]io.WriteCloser)
p.commands = make(map[string]*exec.Cmd)
p.scanners = make(map[string]*bufio.Scanner)
defer p.closeAll()
// Execute the program! BEGIN, then pattern/actions, then END
err = p.execBeginEnd(program.Begin)
if err != nil && err != errExit {
return 0, err
}
if program.Actions == nil && program.End == nil {
return p.exitStatus, nil
}
if err != errExit {
err = p.execActions(program.Actions)
if err != nil && err != errExit {
return 0, err
}
}
err = p.execBeginEnd(program.End)
if err != nil && err != errExit {
return 0, err
}
return p.exitStatus, nil
}
// Exec provides a simple way to parse and execute an AWK program
// with the given field separator. Exec reads input from the given
// reader (nil means use os.Stdin) and writes output to stdout (nil
// means use a buffered version of os.Stdout).
func Exec(source, fieldSep string, input io.Reader, output io.Writer) error {
prog, err := parser.ParseProgram([]byte(source), nil)
if err != nil {
return err
}
config := &Config{
Stdin: input,
Output: output,
Error: ioutil.Discard,
Vars: []string{"FS", fieldSep},
}
_, err = ExecProgram(prog, config)
return err
}
// Execute BEGIN or END blocks (may be multiple)
func (p *interp) execBeginEnd(beginEnd []ast.Stmts) error {
for _, statements := range beginEnd {
err := p.executes(statements)
if err != nil {
return err
}
}
return nil
}
// Execute pattern-action blocks (may be multiple)
func (p *interp) execActions(actions []ast.Action) error {
inRange := make([]bool, len(actions))
lineLoop:
for {
// Read and setup next line of input
line, err := p.nextLine()
if err == io.EOF {
break
}
if err != nil {
return err
}
p.setLine(line, false)
// Execute all the pattern-action blocks for each line
for i, action := range actions {
// First determine whether the pattern matches
matched := false
switch len(action.Pattern) {
case 0:
// No pattern is equivalent to pattern evaluating to true
matched = true
case 1:
// Single boolean pattern
v, err := p.eval(action.Pattern[0])
if err != nil {
return err
}
matched = v.boolean()
case 2:
// Range pattern (matches between start and stop lines)
if !inRange[i] {
v, err := p.eval(action.Pattern[0])
if err != nil {
return err
}
inRange[i] = v.boolean()
}
matched = inRange[i]
if inRange[i] {
v, err := p.eval(action.Pattern[1])
if err != nil {
return err
}
inRange[i] = !v.boolean()
}
}
if !matched {
continue
}
// No action is equivalent to { print $0 }
if action.Stmts == nil {
err := p.printLine(p.output, p.line)
if err != nil {
return err
}
continue
}
// Execute the body statements
err := p.executes(action.Stmts)
if err == errNext {
// "next" statement skips straight to next line
continue lineLoop
}
if err != nil {
return err
}
}
}
return nil
}
// Execute a block of multiple statements
func (p *interp) executes(stmts ast.Stmts) error {
for _, s := range stmts {
err := p.execute(s)
if err != nil {
return err
}
}
return nil
}
// Execute a single statement
func (p *interp) execute(stmt ast.Stmt) error {
switch s := stmt.(type) {
case *ast.ExprStmt:
// Expression statement: simply throw away the expression value
_, err := p.eval(s.Expr)
return err
case *ast.PrintStmt:
// Print OFS-separated args followed by ORS (usually newline)
var line string
if len(s.Args) > 0 {
strs := make([]string, len(s.Args))
for i, a := range s.Args {
v, err := p.eval(a)
if err != nil {
return err
}
strs[i] = v.str(p.outputFormat)
}
line = strings.Join(strs, p.outputFieldSep)
} else {
// "print" with no args is equivalent to "print $0"
line = p.line
}
output, err := p.getOutputStream(s.Redirect, s.Dest)
if err != nil {
return err
}
return p.printLine(output, line)
case *ast.PrintfStmt:
// printf(fmt, arg1, arg2, ...): uses our version of sprintf
// to build the formatted string and then print that
formatValue, err := p.eval(s.Args[0])
if err != nil {
return err
}
format := p.toString(formatValue)
args := make([]value, len(s.Args)-1)
for i, a := range s.Args[1:] {
args[i], err = p.eval(a)
if err != nil {
return err
}
}
output, err := p.getOutputStream(s.Redirect, s.Dest)
if err != nil {
return err
}
str, err := p.sprintf(format, args)
if err != nil {
return err
}
err = writeOutput(output, str)
if err != nil {
return err
}
case *ast.IfStmt:
v, err := p.eval(s.Cond)
if err != nil {
return err
}
if v.boolean() {
return p.executes(s.Body)
} else {
// Doesn't do anything if s.Else is nil
return p.executes(s.Else)
}
case *ast.ForStmt:
// C-like for loop with pre-statement, cond, and post-statement
if s.Pre != nil {
err := p.execute(s.Pre)
if err != nil {
return err
}
}
for {
if s.Cond != nil {
v, err := p.eval(s.Cond)
if err != nil {
return err
}
if !v.boolean() {
break
}
}
err := p.executes(s.Body)
if err == errBreak {
break
}
if err != nil && err != errContinue {
return err
}
if s.Post != nil {
err := p.execute(s.Post)
if err != nil {
return err
}
}
}
case *ast.ForInStmt:
// Foreach-style "for (key in array)" loop
array := p.arrays[p.getArrayIndex(s.Array.Scope, s.Array.Index)]
for index := range array {
err := p.setVar(s.Var.Scope, s.Var.Index, str(index))
if err != nil {
return err
}
err = p.executes(s.Body)
if err == errBreak {
break
}
if err == errContinue {
continue
}
if err != nil {
return err
}
}
case *ast.ReturnStmt:
// Return statement uses special error value which is "caught"
// by the callUser function
var v value
if s.Value != nil {
var err error
v, err = p.eval(s.Value)
if err != nil {
return err
}
}
return returnValue{v}
case *ast.WhileStmt:
// Simple "while (cond)" loop
for {
v, err := p.eval(s.Cond)
if err != nil {
return err
}
if !v.boolean() {
break
}
err = p.executes(s.Body)
if err == errBreak {
break
}
if err == errContinue {
continue
}
if err != nil {
return err
}
}
case *ast.DoWhileStmt:
// Do-while loop (tests condition after executing body)
for {
err := p.executes(s.Body)
if err == errBreak {
break
}
if err == errContinue {
continue
}
if err != nil {
return err
}
v, err := p.eval(s.Cond)
if err != nil {
return err
}
if !v.boolean() {
break
}
}
// Break, continue, next, and exit statements
case *ast.BreakStmt:
return errBreak
case *ast.ContinueStmt:
return errContinue
case *ast.NextStmt:
return errNext
case *ast.ExitStmt:
if s.Status != nil {
status, err := p.eval(s.Status)
if err != nil {
return err
}
p.exitStatus = int(status.num())
}
// Return special errExit value "caught" by top-level executor
return errExit
case *ast.DeleteStmt:
if len(s.Index) > 0 {
// Delete single key from array
index, err := p.evalIndex(s.Index)
if err != nil {
return err
}
array := p.arrays[p.getArrayIndex(s.Array.Scope, s.Array.Index)]
delete(array, index) // Does nothing if key isn't present
} else {
// Delete entire array
array := p.arrays[p.getArrayIndex(s.Array.Scope, s.Array.Index)]
for k := range array {
delete(array, k)
}
}
case *ast.BlockStmt:
// Nested block (just syntax, doesn't do anything)
return p.executes(s.Body)
default:
// Should never happen
panic(fmt.Sprintf("unexpected stmt type: %T", stmt))
}
return nil
}
// Evaluate a single expression, return expression value and error
func (p *interp) eval(expr ast.Expr) (value, error) {
switch e := expr.(type) {
case *ast.NumExpr:
// Number literal
return num(e.Value), nil
case *ast.StrExpr:
// String literal
return str(e.Value), nil
case *ast.FieldExpr:
// $n field expression
index, err := p.eval(e.Index)
if err != nil {
return null(), err
}
return p.getField(int(index.num()))
case *ast.VarExpr:
// Variable read expression (scope is global, local, or special)
return p.getVar(e.Scope, e.Index), nil
case *ast.RegExpr:
// Stand-alone /regex/ is equivalent to: $0 ~ /regex/
re, err := p.compileRegex(e.Regex)
if err != nil {
return null(), err
}
return boolean(re.MatchString(p.line)), nil
case *ast.BinaryExpr:
// Binary expression. Note that && and || are special cases
// as they're short-circuit operators.
left, err := p.eval(e.Left)
if err != nil {
return null(), err
}
switch e.Op {
case AND:
if !left.boolean() {
return num(0), nil
}
right, err := p.eval(e.Right)
if err != nil {
return null(), err
}
return boolean(right.boolean()), nil
case OR:
if left.boolean() {
return num(1), nil
}
right, err := p.eval(e.Right)
if err != nil {
return null(), err
}
return boolean(right.boolean()), nil
default:
right, err := p.eval(e.Right)
if err != nil {
return null(), err
}
return p.evalBinary(e.Op, left, right)
}
case *ast.IncrExpr:
// Pre-increment, post-increment, pre-decrement, post-decrement
// First evaluate the expression, but remember array or field
// index, so we don't evaluate part of the expression twice
exprValue, arrayIndex, fieldIndex, err := p.evalForAugAssign(e.Expr)
if err != nil {
return null(), err
}
// Then convert to number and increment or decrement
exprNum := exprValue.num()
var incr float64
if e.Op == INCR {
incr = exprNum + 1
} else {
incr = exprNum - 1
}
incrValue := num(incr)
// Finally, assign back to expression and return the correct value
err = p.assignAug(e.Expr, arrayIndex, fieldIndex, incrValue)
if err != nil {
return null(), err
}
if e.Pre {
return incrValue, nil
} else {
return num(exprNum), nil
}
case *ast.AssignExpr:
// Assignment expression (returns right-hand side)
right, err := p.eval(e.Right)
if err != nil {
return null(), err
}
err = p.assign(e.Left, right)
if err != nil {
return null(), err
}
return right, nil
case *ast.AugAssignExpr:
// Augmented assignment like += (returns right-hand side)
right, err := p.eval(e.Right)
if err != nil {
return null(), err
}
left, arrayIndex, fieldIndex, err := p.evalForAugAssign(e.Left)
if err != nil {
return null(), err
}
right, err = p.evalBinary(e.Op, left, right)
if err != nil {
return null(), err
}
err = p.assignAug(e.Left, arrayIndex, fieldIndex, right)
if err != nil {
return null(), err
}
return right, nil
case *ast.CondExpr:
// C-like ?: ternary conditional operator
cond, err := p.eval(e.Cond)
if err != nil {
return null(), err
}
if cond.boolean() {
return p.eval(e.True)
} else {
return p.eval(e.False)
}
case *ast.IndexExpr:
// Read value from array by index
index, err := p.evalIndex(e.Index)
if err != nil {
return null(), err
}
return p.getArrayValue(e.Array.Scope, e.Array.Index, index), nil
case *ast.CallExpr:
// Call a builtin function
return p.callBuiltin(e.Func, e.Args)
case *ast.UnaryExpr:
// Unary ! or + or -
v, err := p.eval(e.Value)
if err != nil {
return null(), err
}
return p.evalUnary(e.Op, v), nil
case *ast.InExpr:
// "key in array" expression
index, err := p.evalIndex(e.Index)
if err != nil {
return null(), err
}
array := p.arrays[p.getArrayIndex(e.Array.Scope, e.Array.Index)]
_, ok := array[index]
return boolean(ok), nil
case *ast.UserCallExpr:
// Call user-defined or native Go function
if e.Native {
return p.callNative(e.Index, e.Args)
} else {
return p.callUser(e.Index, e.Args)
}
case *ast.GetlineExpr:
// Getline: read line from input
var line string
switch {
case e.Command != nil:
nameValue, err := p.eval(e.Command)
if err != nil {
return null(), err
}
name := p.toString(nameValue)
scanner, err := p.getInputScannerPipe(name)
if err != nil {
return null(), err
}
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return num(-1), nil
}
return num(0), nil
}
line = scanner.Text()
case e.File != nil:
nameValue, err := p.eval(e.File)
if err != nil {
return null(), err
}
name := p.toString(nameValue)
scanner, err := p.getInputScannerFile(name)
if err != nil {
if _, ok := err.(*os.PathError); ok {
// File not found is not a hard error, getline just returns -1.
// See: https://github.com/benhoyt/goawk/issues/41
return num(-1), nil
}
return null(), err
}
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
return num(-1), nil
}
return num(0), nil
}
line = scanner.Text()
default:
p.flushOutputAndError() // Flush output in case they've written a prompt
var err error
line, err = p.nextLine()
if err == io.EOF {
return num(0), nil
}
if err != nil {
return num(-1), nil
}
}
if e.Target != nil {
err := p.assign(e.Target, numStr(line))
if err != nil {
return null(), err
}
} else {
p.setLine(line, false)
}
return num(1), nil
default:
// Should never happen
panic(fmt.Sprintf("unexpected expr type: %T", expr))
}
}
func (p *interp) evalForAugAssign(expr ast.Expr) (v value, arrayIndex string, fieldIndex int, err error) {
switch expr := expr.(type) {
case *ast.VarExpr:
v = p.getVar(expr.Scope, expr.Index)
case *ast.IndexExpr:
arrayIndex, err = p.evalIndex(expr.Index)
if err != nil {
return null(), "", 0, err
}
v = p.getArrayValue(expr.Array.Scope, expr.Array.Index, arrayIndex)
case *ast.FieldExpr:
index, err := p.eval(expr.Index)
if err != nil {
return null(), "", 0, err
}
fieldIndex = int(index.num())
v, err = p.getField(fieldIndex)
if err != nil {
return null(), "", 0, err
}
}
return v, arrayIndex, fieldIndex, nil
}
func (p *interp) assignAug(expr ast.Expr, arrayIndex string, fieldIndex int, v value) error {
switch expr := expr.(type) {
case *ast.VarExpr:
return p.setVar(expr.Scope, expr.Index, v)
case *ast.IndexExpr:
p.setArrayValue(expr.Array.Scope, expr.Array.Index, arrayIndex, v)
default: // *FieldExpr
return p.setField(fieldIndex, p.toString(v))
}
return nil
}
// Get a variable's value by index in given scope
func (p *interp) getVar(scope ast.VarScope, index int) value {
switch scope {
case ast.ScopeGlobal:
return p.globals[index]
case ast.ScopeLocal:
return p.frame[index]
default: // ScopeSpecial
switch index {
case ast.V_NF:
p.ensureFields()
return num(float64(p.numFields))
case ast.V_NR:
return num(float64(p.lineNum))
case ast.V_RLENGTH:
return num(float64(p.matchLength))
case ast.V_RSTART:
return num(float64(p.matchStart))
case ast.V_FNR:
return num(float64(p.fileLineNum))
case ast.V_ARGC:
return num(float64(p.argc))
case ast.V_CONVFMT:
return str(p.convertFormat)
case ast.V_FILENAME:
return p.filename
case ast.V_FS:
return str(p.fieldSep)
case ast.V_OFMT:
return str(p.outputFormat)
case ast.V_OFS:
return str(p.outputFieldSep)
case ast.V_ORS:
return str(p.outputRecordSep)
case ast.V_RS:
return str(p.recordSep)
case ast.V_RT:
return str(p.recordTerminator)
case ast.V_SUBSEP:
return str(p.subscriptSep)
default: