-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
eval.go
2924 lines (2459 loc) · 61.4 KB
/
eval.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 eval contains the evaluator which executes the BASIC programs.
//
// The interpreter is intentionally simple:
//
// 1. The input program is parsed into a series of tokens.
//
// 2. Each token is executed sequentially.
//
// There are distinct handlers for each kind of built-in primitive such
// as REM, DATA, READ, etc. Things that could be pushed outside the core,
// such as the maths-primitives (SIN, COS, TAN, etc) have been moved into
// their own package to keep this as simple and readable as possible.
package eval
import (
"bufio"
"context"
"fmt"
"math"
"os"
"strconv"
"strings"
"github.com/skx/gobasic/builtin"
"github.com/skx/gobasic/object"
"github.com/skx/gobasic/token"
"github.com/skx/gobasic/tokenizer"
)
// userFunction is a structure that holds one entry for each user-defined function.
type userFunction struct {
// name is the name of the user-defined function.
name string
// body is the expression to be evaluated.
body string
// args is the array of variable-names to set for the arguments.
args []string
}
// Interpreter holds our state.
type Interpreter struct {
// The program we execute is nothing more than an array of tokens.
program []token.Token
// Should we finish execution?
// This is set by the `END` statement.
finished bool
// We execute from the given offset.
//
// Sequential execution just means bumping this up by one each
// time we execute an instruction, or pick off the arguments to
// one.
//
// But set it to 17, or some other random value, and you've got
// a GOTO implemented!
offset int
// We record the line-number we're currently executing here.
// NOTE: This is a string because we take it from the lineno
// token, with no modification.
lineno string
// A stack for handling GOSUB/RETURN calls
gstack *Stack
// vars holds the variables set in the program, via LET.
vars *Variables
// loops holds references to open FOR-loops
loops *Loops
// STDIN is an input-reader used for the INPUT statement
STDIN *bufio.Reader
// STDOUT is the writer used for PRINT and DUMP statements
STDOUT *bufio.Writer
// STDERR is the writer used for user facing errors during program execution
STDERR *bufio.Writer
// LINEEND defines any additional characters to output when printing
// to the output or error streams.
LINEEND string
// Hack: Was the previous statement a GOTO/GOSUB?
jump bool
// lines is a lookup table - the key is the line-number of
// the source program, and the value is the offset in our
// program-array that this is located at.
lines map[string]int
// functions holds builtin-functions
functions *builtin.Builtins
// trace is true if the user is tracing execution
trace bool
// dataOffset keeps track of how far we've read into any
// data-statements
dataOffset int
// data holds any value stored in DATA statements
// These are populated when the program is loaded
data []object.Object
// fns contains a map of user-defined functions.
fns map[string]userFunction
// context for handling timeout
context context.Context
}
// StdInput allows access to the input-reading object.
func (e *Interpreter) StdInput() *bufio.Reader {
if e.STDIN == nil {
e.STDIN = bufio.NewReader(os.Stdin)
}
return e.STDIN
}
// StdOutput allows access to the output-writing object.
func (e *Interpreter) StdOutput() *bufio.Writer {
if e.STDOUT == nil {
e.STDOUT = bufio.NewWriter(os.Stdout)
}
return e.STDOUT
}
// StdError allows access to the error-writing object.
func (e *Interpreter) StdError() *bufio.Writer {
if e.STDERR == nil {
e.STDERR = bufio.NewWriter(os.Stderr)
}
return e.STDERR
}
// Data returns a reference to this underlying Interpreter
func (e *Interpreter) Data() interface{} {
return e
}
// LineEnding defines an additional characters to write after PRINT commands
func (e *Interpreter) LineEnding() string {
return e.LINEEND
}
// New is our constructor.
//
// Given a lexer we store all the tokens it produced in our array, and
// initialise some other state.
func New(stream *tokenizer.Tokenizer) (*Interpreter, error) {
t := &Interpreter{offset: 0}
// setup a stack for holding line-numbers for GOSUB/RETURN
t.gstack = NewStack()
// setup storage for variable-contents
t.vars = NewVars()
// setup storage for for-loops
t.loops = NewLoops()
// Built-in functions are stored here.
t.functions = builtin.New()
// allow reading from STDIN
t.STDIN = bufio.NewReader(os.Stdin)
// set standard output for STDOUT
t.STDOUT = bufio.NewWriter(os.Stdout)
//
// Setup a map to hold our jump-targets
//
t.lines = make(map[string]int)
//
// Setup a map to hold user-defined functions.
//
t.fns = make(map[string]userFunction)
//
// No context by default
//
t.context = context.Background()
//
// The previous token we've seen, if any.
//
var prevToken token.Token
//
// Save the tokens that our program consists of, one by one,
// until we hit the end.
//
// We also insert any implied GOTO statements into IF
// statements which lack them.
//
for {
//
// Fetch the next token from our tokenizer.
//
tok := stream.NextToken()
if tok.Type == token.EOF {
break
}
//
// If the previous token was a "THEN" or "ELSE", and the
// current token is an integer then we add in the implicit
// GOTO.
//
// This allows the following two programs to be identical:
//
// IF 1 < 2 THEN 300 ELSE 400
//
// IF 1 < 2 THEN GOTO 300 ELSE GOTO 400
//
if prevToken.Type == token.THEN || prevToken.Type == token.ELSE {
if tok.Type == token.INT {
t.program = append(t.program,
token.Token{Type: token.GOTO, Literal: "GOTO"})
}
}
//
// Append the token to our array
//
t.program = append(t.program, tok)
// Continue - recording the previous token too.
prevToken = tok
}
//
// Now our `t.program` array is an array of tokens which
// we'll execute.
//
// We're going to parse that program, looking for the
// definitions of user-defined functions, and any DATA
// statements.
//
// The DATA-statements we load at parse-time since that
// is a little neater.
//
// The user-defined functions we need to parse at run-time
// since they might be invoked before they're defined otherwise
// like this:
//
// 10 PRINT SQUARE(3)
// 20 DEF FN SQUARE(a) a * a
//
// Having the user reorder their program to avoid that would
// be a pain..
//
//
// We're not initially inside a comment.
//
inComment := false
//
// Process the complete program, now we've stored it.
//
for offset, tok := range t.program {
//
// Did we find a line-number?
//
if tok.Type == token.LINENO {
//
// Get the line-number.
//
line := tok.Literal
//
// Do we already have an offset saved?
//
// If so that means we have duplicate line-numbers
//
if t.lines[line] != 0 {
err := fmt.Sprintf("WARN: Line %s is duplicated - GOTO/GOSUB behaviour is undefined", line)
t.StdError().WriteString(err + t.LineEnding())
}
t.lines[line] = offset
}
//
// If we're in a comment then skip all action until
// we hit the next newline (or EOF).
//
if inComment {
if tok.Type == token.NEWLINE {
inComment = false
}
continue
}
//
// Comments start with REM, if we find a REM then
// we're in a comment.
//
if tok.Type == token.REM {
inComment = true
}
//
// We found a data-token.
//
// We expect this will be "string" OR "comma" OR number.
//
if tok.Type == token.DATA {
//
// Walk the rest of the program - starting
// from the token AFTER the DATA
//
start := offset + 1
run := true
for start < len(t.program) && run {
tk := t.program[start]
switch tk.Type {
case token.NEWLINE:
run = false
case token.COMMA:
// NOP
case token.STRING:
t.data = append(t.data, &object.StringObject{Value: tk.Literal})
case token.INT:
i, _ := strconv.ParseFloat(tk.Literal, 64)
t.data = append(t.data, &object.NumberObject{Value: i})
default:
return nil, fmt.Errorf("error reading DATA - Unhandled token: %s", tk.String())
}
start++
}
}
//
// We found a user-defined function definition.
//
if tok.Type == token.DEF && offset >= 1 && t.program[offset-1].Type == token.LINENO {
//
// Parse the function-definition.
//
err := t.parseDefFN(offset)
if err != nil {
return nil, fmt.Errorf("error in DEF FN: %s", err.Error())
}
}
}
//
// By default none of the data will have been read.
//
t.dataOffset = 0
//
// Register our default primitives, which are implemented in the
// builtin-package.
//
// We have to do this after we've loaded our program, because
// the registration-process involves rewriting our program to
// change "IDENT" into "BUILTIN" for each known-primitive.
//
// NOTE: Ideally _this_ package wouldn't know about the
// functions which _that_ other package provides...
//
t.RegisterBuiltin("ABS", 1, builtin.ABS)
t.RegisterBuiltin("ACS", 1, builtin.ACS)
t.RegisterBuiltin("ASN", 1, builtin.ASN)
t.RegisterBuiltin("ATN", 1, builtin.ATN)
t.RegisterBuiltin("BIN", 1, builtin.BIN)
t.RegisterBuiltin("COS", 1, builtin.COS)
t.RegisterBuiltin("EXP", 1, builtin.EXP)
t.RegisterBuiltin("INT", 1, builtin.INT)
t.RegisterBuiltin("LN", 1, builtin.LN)
t.RegisterBuiltin("LOG", 1, builtin.LN)
t.RegisterBuiltin("PI", 0, builtin.PI)
t.RegisterBuiltin("RND", 1, builtin.RND)
t.RegisterBuiltin("SGN", 1, builtin.SGN)
t.RegisterBuiltin("SIN", 1, builtin.SIN)
t.RegisterBuiltin("SQR", 1, builtin.SQR)
t.RegisterBuiltin("TAN", 1, builtin.TAN)
t.RegisterBuiltin("VAL", 1, builtin.VAL)
t.RegisterBuiltin("π", 0, builtin.PI)
// Primitives that operate upon strings
t.RegisterBuiltin("CHR$", 1, builtin.CHR)
t.RegisterBuiltin("CODE", 1, builtin.CODE)
t.RegisterBuiltin("LEFT$", 2, builtin.LEFT)
t.RegisterBuiltin("LEN", 1, builtin.LEN)
t.RegisterBuiltin("MID$", 3, builtin.MID)
t.RegisterBuiltin("RIGHT$", 2, builtin.RIGHT)
t.RegisterBuiltin("SPC", 1, builtin.SPC)
t.RegisterBuiltin("STR$", 1, builtin.STR)
t.RegisterBuiltin("TL$", 1, builtin.TL)
// Output
t.RegisterBuiltin("PRINT", -1, builtin.PRINT)
t.RegisterBuiltin("DUMP", 1, builtin.DUMP)
//
// Return our configured interpreter
//
return t, nil
}
// NewWithContext is a constructor which allows a context to be specified.
//
// It will defer to New for the basic constructor behaviour.
func NewWithContext(ctx context.Context, stream *tokenizer.Tokenizer) (*Interpreter, error) {
// Create
i, err := New(stream)
if err != nil {
return nil, err
}
i.context = ctx
return i, nil
}
// FromString is a constructor which takes a string, and constructs
// an Interpreter from it - rather than requiring the use of the tokenizer.
func FromString(input string) (*Interpreter, error) {
tok := tokenizer.New(input)
return New(tok)
}
////
//
// Helpers for stuff
//
////
// factor
func (e *Interpreter) factor() object.Object {
for {
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing factor()")
}
tok := e.program[e.offset]
switch tok.Type {
case token.LBRACKET:
// skip past the lbracket
e.offset++
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing factor()")
}
// handle the expr
ret := e.expr(true)
if ret.Type() == object.ERROR {
return ret
}
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing factor()")
}
// skip past the rbracket
tok = e.program[e.offset]
if tok.Type != token.RBRACKET {
return object.Error("Unclosed bracket around expression")
}
e.offset++
// Return the result of the sub-expression
return (ret)
case token.INT:
i, _ := strconv.ParseFloat(tok.Literal, 64)
e.offset++
return &object.NumberObject{Value: i}
case token.STRING:
e.offset++
return &object.StringObject{Value: tok.Literal}
case token.FN:
//
// Call the user-defined function.
//
e.offset++
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing FN call")
}
name := e.program[e.offset]
e.offset++
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing FN call")
}
//
// Collect the arguments.
//
var args []object.Object
//
// We walk forward collecting the values between
// "(" & ")".
//
for e.offset < len(e.program) {
tt := e.program[e.offset]
if tt.Type == token.RBRACKET {
e.offset++
break
}
if tt.Type == token.COMMA || tt.Type == token.LBRACKET {
e.offset++
continue
}
// Call the token as an expression
obj := e.expr(true)
if obj.Type() == object.ERROR {
return obj
}
args = append(args, obj)
}
//
// Now we call the function with those values.
//
val := e.callUserFunction(name.Literal, args)
return val
case token.BUILTIN:
//
// Call the built-in and return the value.
//
val := e.callBuiltin(tok.Literal)
return val
case token.IDENT:
//
// Look for indexed variables
//
e.offset++
index, ee := e.findIndex()
if ee != nil {
return object.Error(ee.Error())
}
//
// Indexed? Then get it.
//
if len(index) > 0 {
val := e.GetArrayVariable(tok.Literal, index)
return val
}
//
// Get the contents of the variable.
//
val := e.GetVariable(tok.Literal)
return val
default:
return object.Error("factor() - unhandled token: %v\n", tok)
}
}
}
// terminal - handles parsing of the form
//
// ARG1 OP ARG2
//
// See also expr() which is similar.
func (e *Interpreter) term() object.Object {
// First argument
f1 := e.factor()
if f1 == nil {
return object.Error("term() - received a nil value from factor() - f1")
}
if f1.Type() == object.ERROR {
return f1
}
if e.offset >= len(e.program) {
return f1
}
// Get the operator
tok := e.program[e.offset]
// Here we handle the obvious ones.
for tok.Type == token.ASTERISK ||
tok.Type == token.SLASH ||
tok.Type == token.POW ||
tok.Type == token.MOD {
// skip the operator
e.offset++
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing term()")
}
// get the second argument
f2 := e.factor()
if f2 == nil {
return object.Error("term() - received a nil value from factor() - f2")
}
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing term()")
}
//
// Have we handled this operation?
//
handled := false
//
// We allow string "multiplication"
//
// STRING * NUMBER
//
// "STEVE " * 4 => "STEVE STEVE STEVE STEVE "
//
if f1.Type() == object.STRING &&
f2.Type() == object.NUMBER &&
tok.Type == token.ASTERISK {
// original value
val := f1.(*object.StringObject).Value
orig := val
// repeat
rep := f2.(*object.NumberObject).Value
// The string repetition won't work if
// the input string is empty.
//
// For example:
//
// "" * 55
//
// Will generate the output: ""
//
// Catch that in advance of the loop to avoid
// wasting time - we also cap the maximum length
// of our string here.
if len(orig) > 1 {
// while there are more repetitions
for rep > 0 {
// append
orig = orig + val
// reduce by one
rep--
// ensure we terminate if the string is too long
if len(orig) > 65535 {
fmt.Printf("WARNING: string too long, max length is 65535: %d currently\n", len(orig))
// Return early
// even with less than expected
// repetitions
f1 = &object.StringObject{Value: orig}
return f1
}
}
}
// Save the updated value
f1 = &object.StringObject{Value: orig}
// We've handled this
handled = true
}
//
// We allow operations of the form:
//
// NUMBER OP NUMBER
//
if f1.Type() == object.NUMBER &&
f2.Type() == object.NUMBER {
//
// Get the values.
//
v1 := f1.(*object.NumberObject).Value
v2 := f2.(*object.NumberObject).Value
//
// Handle the operator.
//
if tok.Type == token.ASTERISK {
f1 = &object.NumberObject{Value: v1 * v2}
}
if tok.Type == token.POW {
f1 = &object.NumberObject{Value: math.Pow(v1, v2)}
}
if tok.Type == token.SLASH {
if v2 == 0 {
return object.Error("Division by zero")
}
f1 = &object.NumberObject{Value: v1 / v2}
}
if tok.Type == token.MOD {
d1 := int(v1)
d2 := int(v2)
if d2 == 0 {
return object.Error("MOD 0 is an error")
}
f1 = &object.NumberObject{Value: float64(d1 % d2)}
}
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing term()")
}
// we've handled the operation now
handled = true
}
//
// If we didn't handle the operation then the types
// were invalid, so report that.
//
if !handled {
return object.Error("term() only handles string-multiplication and integer-operations")
}
// repeat?
tok = e.program[e.offset]
}
return f1
}
// expression - handles parsing of the form
//
// ARG1 OP ARG2
//
// See also term() which is similar.
func (e *Interpreter) expr(allowBinOp bool) object.Object {
// First argument.
t1 := e.term()
// Impossible error?
if t1 == nil {
return object.Error("Found a nil terminal")
}
// Did this error?
if t1.Type() == object.ERROR {
return t1
}
if e.offset >= len(e.program) {
return t1
}
// Get the operator
tok := e.program[e.offset]
// Here we handle the obvious ones.
for tok.Type == token.PLUS ||
tok.Type == token.MINUS ||
tok.Type == token.AND ||
tok.Type == token.OR ||
tok.Type == token.XOR {
//
// Sometimes we disable binary AND + binary OR.
//
// This is mostly due to our naive parser, because
// it gets confused handling "IF BLAH AND BLAH .."
//
if !allowBinOp {
if tok.Type == token.AND ||
tok.Type == token.OR ||
tok.Type == token.XOR {
return t1
}
}
// skip the operator
e.offset++
if e.offset >= len(e.program) {
return object.Error("end of program processing expr()")
}
// Get the second argument.
t2 := e.term()
// Did this error?
if t2.Type() == object.ERROR {
return t2
}
//
// We allow operations of the form:
//
// NUMBER OP NUMBER
//
// STRING OP STRING
//
// We support ZERO operations where the operand types
// do not match. If we hit this it's a bug.
//
if t1.Type() != t2.Type() {
return object.Error("expr() - type mismatch between '%v' + '%v'", t1, t2)
}
//
// OK so types do match - but we only care about
// NUMBER op NUMBER, or STRING op STRING.
//
// If we see an array, error, or other type we're in
// trouble:
//
if t1.Type() != object.STRING &&
t1.Type() != object.NUMBER {
return object.Error("expr() - we don't support operations on non-number/non-string types '%v' + '%v'", t1, t2)
}
//
// Are the operands strings?
//
if t1.Type() == object.STRING {
//
// Get their values.
//
s1 := t1.(*object.StringObject).Value
s2 := t2.(*object.StringObject).Value
//
// We only support "+" for concatenation
//
if tok.Type == token.PLUS {
t1 = &object.StringObject{Value: s1 + s2}
} else {
return object.Error("expr() operation '%s' not supported for strings", tok.Literal)
}
} else {
//
// Here we have two operands that are numbers.
//
// Get their values for neatness.
//
n1 := t1.(*object.NumberObject).Value
n2 := t2.(*object.NumberObject).Value
if tok.Type == token.PLUS {
t1 = &object.NumberObject{Value: n1 + n2}
} else if tok.Type == token.MINUS {
t1 = &object.NumberObject{Value: n1 - n2}
} else if tok.Type == token.AND {
t1 = &object.NumberObject{Value: float64(int(n1) & int(n2))}
} else if tok.Type == token.OR {
t1 = &object.NumberObject{Value: float64(int(n1) | int(n2))}
} else if tok.Type == token.XOR {
t1 = &object.NumberObject{Value: float64(int(n1) ^ int(n2))}
}
}
if e.offset >= len(e.program) {
return object.Error("end of program processing expr()")
}
// repeat?
tok = e.program[e.offset]
}
return t1
}
// compare runs a comparison function (!)
//
// It is only used by the `IF` statement.
func (e *Interpreter) compare(allowBinOp bool) object.Object {
// Get the first statement
t1 := e.expr(allowBinOp)
if t1.Type() == object.ERROR {
return t1
}
if e.offset >= len(e.program) {
return t1
}
// Get the comparison function
op := e.program[e.offset]
// If the next token is an THEN then we're going
// to regard the test as a pass if the first
// value was not 0 (number) and not "" (string)
if op.Type == token.THEN {
switch t1.Type() {
case object.STRING:
if t1.(*object.StringObject).Value != "" {
return &object.NumberObject{Value: 1}
}
case object.NUMBER:
if t1.(*object.NumberObject).Value != 0 {
return &object.NumberObject{Value: 1}
}
}
return &object.NumberObject{Value: 0}
}
//
// OK bump past the comparison function.
//
e.offset++
if e.offset >= len(e.program) {
return object.Error("Hit end of program processing compare()")
}
// Get the second expression
t2 := e.expr(allowBinOp)
if t2.Type() == object.ERROR {
return t2
}
//
// String-tests here
//
if t1.Type() == object.STRING && t2.Type() == object.STRING {
v1 := t1.(*object.StringObject).Value
v2 := t2.(*object.StringObject).Value
switch op.Type {
case token.ASSIGN:
if v1 == v2 {
//true
return &object.NumberObject{Value: 1}
}
case token.NOTEQUALS:
if v1 != v2 {
//true
return &object.NumberObject{Value: 1}
}
case token.GT:
if v1 > v2 {
//true
return &object.NumberObject{Value: 1}
}
case token.GTEQUALS:
if v1 >= v2 {
//true
return &object.NumberObject{Value: 1}
}
case token.LT:
if v1 < v2 {
//true
return &object.NumberObject{Value: 1}