-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
eval.go
2115 lines (2024 loc) · 49.1 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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Evaluates Go expressions, using the current values of variables in a program
// being debugged.
//
// TODOs:
// More overflow checking.
// Stricter type checking.
// More expression types.
// +build linux
package server
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"math"
"math/big"
"cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug"
"cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/dwarf"
)
const prec = 256 // precision for untyped float and complex constants.
var (
// Some big.Ints to use in overflow checks.
bigIntMaxInt32 = big.NewInt(math.MaxInt32)
bigIntMinInt32 = big.NewInt(math.MinInt32)
bigIntMaxInt64 = big.NewInt(math.MaxInt64)
bigIntMinInt64 = big.NewInt(math.MinInt64)
bigIntMaxUint64 = new(big.Int).SetUint64(math.MaxUint64)
)
// result stores an intermediate value produced during evaluation of an expression.
//
// d contains the DWARF type of the value. For untyped values, d will be nil.
//
// v contains the value itself. For numeric and bool types, v will have the
// corresponding predeclared Go type.
// For untyped integer, rune, float, complex, string, and bool constants, v will
// have type untInt, untRune, untFloat, untComplex, untString, or bool,
// respectively.
// For values of type int, uint and uintptr, v will be an int32, int64, uint32
// or uint64 as appropriate.
// For address operations, v will have type pointerToValue.
// For the operands of address operations, v will have type addressableValue.
// Other types are represented using the corresponding implementation of
// debug.Value in program.go.
//
// If an evaluation results in an error, the zero value of result is used.
type result struct {
d dwarf.Type
v interface{}
}
// untInt is an untyped integer constant
type untInt struct {
*big.Int
}
// untRune is an untyped rune constant
type untRune struct {
*big.Int
}
// untFloat is an untyped floating-point constant
type untFloat struct {
*big.Float
}
// untComplex is an untyped complex constant
type untComplex struct {
r *big.Float
i *big.Float
}
// untString is an untyped string constant
type untString string
// pointerToValue is a pointer to a value in memory.
// The evaluator constructs these as the result of address operations like "&x".
// Unlike debug.Pointer, the DWARF type stored alongside values of this type
// is the type of the variable, not the type of the pointer.
type pointerToValue struct {
a uint64
}
// addressableValue is the memory location of a value.
// The evaluator constructs these while evaluating the operands of address
// operations like "&x", instead of computing the value of x itself.
type addressableValue struct {
a uint64
}
// A sliceOf is a slice created by slicing an array.
// Unlike debug.Slice, the DWARF type stored alongside a value of this type is
// the type of the slice's elements, not the type of the slice.
type sliceOf debug.Slice
// ident is a value for representing a special identifier.
type ident string
// identLookup is a built-in function of the expression evaluator which gets the
// value of a global symbol.
var identLookup ident = "lookup"
// evalExpression evaluates a Go expression.
// If the program counter and stack pointer are nonzero, they are used to determine
// what local variables are available and where in memory they are.
func (s *Server) evalExpression(expression string, pc, sp uint64) (debug.Value, error) {
e := evaluator{server: s, expression: expression, pc: pc, sp: sp}
node, err := parser.ParseExpr(expression)
if err != nil {
return nil, err
}
val := e.evalNode(node, false)
if e.evalError != nil {
return nil, e.evalError
}
// Convert untyped constants to their default types.
switch v := val.v.(type) {
case untInt:
return e.intFromInteger(v)
case untRune:
if v.Cmp(bigIntMaxInt32) == +1 {
return nil, errors.New("constant overflows rune")
}
if v.Cmp(bigIntMinInt32) == -1 {
return nil, errors.New("constant overflows rune")
}
return int32(v.Int64()), nil
case untFloat:
f, _ := v.Float64()
if math.IsInf(f, 0) {
return nil, errors.New("constant overflows float64")
}
if math.IsNaN(f) {
return nil, errors.New("constant is NaN")
}
return f, nil
case untComplex:
r, _ := v.r.Float64()
i, _ := v.i.Float64()
if math.IsInf(r, 0) || math.IsInf(i, 0) {
return nil, errors.New("constant overflows complex128")
}
if math.IsNaN(r) || math.IsNaN(i) {
return nil, errors.New("constant is NaN")
}
return complex(r, i), nil
case untString:
return debug.String{Length: uint64(len(v)), String: string(v)}, nil
case pointerToValue:
return debug.Pointer{TypeID: uint64(val.d.Common().Offset), Address: v.a}, nil
case sliceOf:
return debug.Slice(v), nil
case nil, addressableValue:
// This case should not be reachable.
return nil, errors.New("unknown error")
}
return val.v, nil
}
type evaluator struct {
// expression is the expression being evaluated.
expression string
// server interacts with the program being debugged.
server *Server
// curNode is the current parse tree node. This is set so that error messages
// can quote the part of the expression that caused an error.
curNode ast.Node
// evalError is the first error that occurred while evaluating the expression,
// or nil if no error has occurred.
evalError error
// pc and sp are the current program counter and stack pointer, used for
// finding local variables. If either are zero, the expression is evaluated
// without using local variables.
pc uint64
sp uint64
}
// setNode sets curNode, and returns curNode's previous value.
func (e *evaluator) setNode(node ast.Node) (old ast.Node) {
old, e.curNode = e.curNode, node
return old
}
// err saves an error that occurred during evaluation.
// It returns a zero result, so that functions can exit and set an error with
// return e.err(...)
func (e *evaluator) err(s string) result {
if e.evalError != nil {
return result{}
}
// Append the substring of the expression that corresponds to the current AST node.
start := int(e.curNode.Pos() - 1)
end := int(e.curNode.End() - 1)
if start < 0 {
start = 0
}
if end > len(e.expression) {
end = len(e.expression)
}
if start > end {
start, end = 0, 0
}
e.evalError = errors.New(s + `: "` + e.expression[start:end] + `"`)
return result{}
}
// evalNode computes the value of a node in the expression tree.
// If getAddress is true, the node is the argument of an & operator, so evalNode
// will return a result with a value of type addressableValue if possible.
func (e *evaluator) evalNode(node ast.Node, getAddress bool) result {
// Set the current node in the evaluator, so that error messages can refer to
// it. Defer a function call that changes it back.
defer e.setNode(e.setNode(node))
switch n := node.(type) {
case *ast.Ident:
if e.pc != 0 && e.sp != 0 {
a, t := e.server.findLocalVar(n.Name, e.pc, e.sp)
if t != nil {
return e.resultFrom(a, t, getAddress)
}
}
a, t := e.server.findGlobalVar(n.Name)
if t != nil {
return e.resultFrom(a, t, getAddress)
}
switch n.Name {
// Note: these could have been redefined as constants in the code, but we
// don't have a way to detect that.
case "true":
return result{nil, true}
case "false":
return result{nil, false}
case "lookup":
return result{nil, identLookup}
}
return e.err("unknown identifier")
case *ast.BasicLit:
switch n.Kind {
case token.INT:
i := new(big.Int)
if _, ok := i.SetString(n.Value, 0); !ok {
return e.err("invalid integer constant")
}
return result{nil, untInt{i}}
case token.FLOAT:
r, _, err := big.ParseFloat(n.Value, 10, prec, big.ToNearestEven)
if err != nil {
return e.err(err.Error())
}
return result{nil, untFloat{r}}
case token.IMAG:
if len(n.Value) <= 1 || n.Value[len(n.Value)-1] != 'i' {
return e.err("invalid imaginary constant")
}
r, _, err := big.ParseFloat(n.Value[:len(n.Value)-1], 10, prec, big.ToNearestEven)
if err != nil {
return e.err(err.Error())
}
return result{nil, untComplex{new(big.Float), r}}
case token.CHAR:
// TODO: unescaping
return result{nil, untRune{new(big.Int).SetInt64(int64(n.Value[1]))}}
case token.STRING:
// TODO: unescaping
if len(n.Value) <= 1 {
return e.err("invalid string constant")
}
return result{nil, untString(n.Value[1 : len(n.Value)-1])}
}
case *ast.ParenExpr:
return e.evalNode(n.X, getAddress)
case *ast.StarExpr:
x := e.evalNode(n.X, false)
switch v := x.v.(type) {
case debug.Pointer:
// x.d may be a typedef pointing to a pointer type (or a typedef pointing
// to a typedef pointing to a pointer type, etc.), so remove typedefs
// until we get the underlying pointer type.
t := followTypedefs(x.d)
if pt, ok := t.(*dwarf.PtrType); ok {
return e.resultFrom(v.Address, pt.Type, getAddress)
} else {
return e.err("invalid DWARF type for pointer")
}
case pointerToValue:
return e.resultFrom(v.a, x.d, getAddress)
case nil:
return x
}
return e.err("invalid indirect")
case *ast.SelectorExpr:
x := e.evalNode(n.X, false)
sel := n.Sel.Name
switch v := x.v.(type) {
case debug.Struct:
for _, f := range v.Fields {
if f.Name == sel {
t, err := e.server.dwarfData.Type(dwarf.Offset(f.Var.TypeID))
if err != nil {
return e.err(err.Error())
}
return e.resultFrom(f.Var.Address, t, getAddress)
}
}
return e.err("struct field not found")
case debug.Pointer:
pt, ok := followTypedefs(x.d).(*dwarf.PtrType) // x.d should be a pointer to struct.
if !ok {
return e.err("invalid DWARF information for pointer")
}
st, ok := followTypedefs(pt.Type).(*dwarf.StructType)
if !ok {
break
}
for _, f := range st.Field {
if f.Name == sel {
return e.resultFrom(v.Address+uint64(f.ByteOffset), f.Type, getAddress)
}
}
return e.err("struct field not found")
case pointerToValue:
st, ok := followTypedefs(x.d).(*dwarf.StructType) // x.d should be a struct.
if !ok {
break
}
for _, f := range st.Field {
if f.Name == sel {
return e.resultFrom(v.a+uint64(f.ByteOffset), f.Type, getAddress)
}
}
return e.err("struct field not found")
}
return e.err("invalid selector expression")
case *ast.IndexExpr:
x, index := e.evalNode(n.X, false), e.evalNode(n.Index, false)
if x.v == nil || index.v == nil {
return result{}
}
// The expression is x[index]
if m, ok := x.v.(debug.Map); ok {
if getAddress {
return e.err("can't take address of map value")
}
mt, ok := followTypedefs(x.d).(*dwarf.MapType)
if !ok {
return e.err("invalid DWARF type for map")
}
var (
found bool // true if the key was found
value result // the map value for the key
abort bool // true if an error occurred while searching
// fn is a function that checks if one (key, value) pair corresponds
// to the index in the expression.
fn = func(keyAddr, valAddr uint64, keyType, valType dwarf.Type) bool {
key := e.resultFrom(keyAddr, keyType, false)
if key.v == nil {
abort = true
return false // stop searching map
}
equal, ok := e.evalBinaryOp(token.EQL, index, key).v.(bool)
if !ok {
abort = true
return false // stop searching map
}
if equal {
found = true
value = e.resultFrom(valAddr, valType, false)
return false // stop searching map
}
return true // continue searching map
}
)
if err := e.server.peekMapValues(mt, m.Address, fn); err != nil {
return e.err(err.Error())
}
if abort {
// Some operation on individual map keys failed.
return result{}
}
if found {
return value
}
// The key wasn't in the map; return the zero value.
return e.zero(mt.ElemType)
}
// The index should be a non-negative integer for the remaining cases.
u, err := uint64FromResult(index)
if err != nil {
return e.err("invalid index: " + err.Error())
}
switch v := x.v.(type) {
case debug.Array:
if u >= v.Length {
return e.err("array index out of bounds")
}
elemType, err := e.server.dwarfData.Type(dwarf.Offset(v.ElementTypeID))
if err != nil {
return e.err(err.Error())
}
return e.resultFrom(v.Element(u).Address, elemType, getAddress)
case debug.Slice:
if u >= v.Length {
return e.err("slice index out of bounds")
}
elemType, err := e.server.dwarfData.Type(dwarf.Offset(v.ElementTypeID))
if err != nil {
return e.err(err.Error())
}
return e.resultFrom(v.Element(u).Address, elemType, getAddress)
case sliceOf:
if u >= v.Length {
return e.err("slice index out of bounds")
}
return e.resultFrom(v.Element(u).Address, x.d, getAddress)
case debug.String:
if getAddress {
return e.err("can't take address of string element")
}
if u >= v.Length {
return e.err("string index out of bounds")
}
if u >= uint64(len(v.String)) {
return e.err("string element unavailable")
}
return e.uint8Result(v.String[u])
case untString:
if getAddress {
return e.err("can't take address of string element")
}
if u >= uint64(len(v)) {
return e.err("string index out of bounds")
}
return e.uint8Result(v[u])
}
return e.err("invalid index expression")
case *ast.SliceExpr:
if n.Slice3 && n.High == nil {
return e.err("middle index required in full slice")
}
if n.Slice3 && n.Max == nil {
return e.err("final index required in full slice")
}
var (
low, high, max uint64
err error
)
if n.Low != nil {
low, err = uint64FromResult(e.evalNode(n.Low, false))
if err != nil {
return e.err("invalid slice lower bound: " + err.Error())
}
}
if n.High != nil {
high, err = uint64FromResult(e.evalNode(n.High, false))
if err != nil {
return e.err("invalid slice upper bound: " + err.Error())
}
}
if n.Max != nil {
max, err = uint64FromResult(e.evalNode(n.Max, false))
if err != nil {
return e.err("invalid slice capacity: " + err.Error())
}
}
x := e.evalNode(n.X, false)
switch v := x.v.(type) {
case debug.Array, debug.Pointer, pointerToValue:
// This case handles the slicing of arrays and pointers to arrays.
var arr debug.Array
switch v := x.v.(type) {
case debug.Array:
arr = v
case debug.Pointer:
pt, ok := followTypedefs(x.d).(*dwarf.PtrType)
if !ok {
return e.err("invalid DWARF type for pointer")
}
a := e.resultFrom(v.Address, pt.Type, false)
arr, ok = a.v.(debug.Array)
if !ok {
// v is a pointer to something other than an array.
return e.err("cannot slice pointer")
}
case pointerToValue:
a := e.resultFrom(v.a, x.d, false)
var ok bool
arr, ok = a.v.(debug.Array)
if !ok {
// v is a pointer to something other than an array.
return e.err("cannot slice pointer")
}
}
elemType, err := e.server.dwarfData.Type(dwarf.Offset(arr.ElementTypeID))
if err != nil {
return e.err(err.Error())
}
if n.High == nil {
high = arr.Length
} else if high > arr.Length {
return e.err("slice upper bound is too large")
}
if n.Max == nil {
max = arr.Length
} else if max > arr.Length {
return e.err("slice capacity is too large")
}
if low > high || high > max {
return e.err("invalid slice index")
}
return result{
d: elemType,
v: sliceOf{
Array: debug.Array{
ElementTypeID: arr.ElementTypeID,
Address: arr.Element(low).Address,
Length: high - low,
StrideBits: uint64(elemType.Common().ByteSize) * 8,
},
Capacity: max - low,
},
}
case debug.Slice:
if n.High == nil {
high = v.Length
} else if high > v.Capacity {
return e.err("slice upper bound is too large")
}
if n.Max == nil {
max = v.Capacity
} else if max > v.Capacity {
return e.err("slice capacity is too large")
}
if low > high || high > max {
return e.err("invalid slice index")
}
v.Address += low * (v.StrideBits / 8)
v.Length = high - low
v.Capacity = max - low
return result{x.d, v}
case sliceOf:
if n.High == nil {
high = v.Length
} else if high > v.Capacity {
return e.err("slice upper bound is too large")
}
if n.Max == nil {
max = v.Capacity
} else if max > v.Capacity {
return e.err("slice capacity is too large")
}
if low > high || high > max {
return e.err("invalid slice index")
}
v.Address += low * (v.StrideBits / 8)
v.Length = high - low
v.Capacity = max - low
return result{x.d, v}
case debug.String:
if n.Max != nil {
return e.err("full slice of string")
}
if n.High == nil {
high = v.Length
}
if low > high || high > v.Length {
return e.err("invalid slice index")
}
v.Length = high - low
if low > uint64(len(v.String)) {
// v.String was truncated before the point where this slice starts.
v.String = ""
} else {
if high > uint64(len(v.String)) {
// v.String was truncated before the point where this slice ends.
high = uint64(len(v.String))
}
v.String = v.String[low:high]
}
return result{x.d, v}
case untString:
if n.Max != nil {
return e.err("full slice of string")
}
if n.High == nil {
high = uint64(len(v))
}
if low > high {
return e.err("invalid slice expression")
}
if high > uint64(len(v)) {
return e.err("slice upper bound is too large")
}
return e.stringResult(string(v[low:high]))
default:
return e.err("invalid slice expression")
}
case *ast.CallExpr:
// Only supports lookup("x"), which gets the value of a global symbol x.
fun := e.evalNode(n.Fun, false)
var args []result
for _, a := range n.Args {
args = append(args, e.evalNode(a, false))
}
if fun.v == identLookup {
if len(args) != 1 {
return e.err("lookup should have one argument")
}
ident, ok := args[0].v.(untString)
if !ok {
return e.err("argument for lookup should be a string constant")
}
if a, t := e.server.findGlobalVar(string(ident)); t == nil {
return e.err("symbol not found")
} else {
return e.resultFrom(a, t, getAddress)
}
}
return e.err("function calls not implemented")
case *ast.UnaryExpr:
if n.Op == token.AND {
x := e.evalNode(n.X, true)
switch v := x.v.(type) {
case addressableValue:
return result{x.d, pointerToValue{v.a}}
case nil:
return x
}
return e.err("can't take address")
}
x := e.evalNode(n.X, false)
if x.v == nil {
return x
}
switch v := x.v.(type) {
case int8:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case int16:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case int32:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case int64:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case uint8:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case uint16:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case uint32:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case uint64:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
case token.XOR:
v = ^v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case float32:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case float64:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case complex64:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case complex128:
switch n.Op {
case token.ADD:
case token.SUB:
v = -v
default:
return e.err("invalid operation")
}
return result{x.d, v}
case untInt:
switch n.Op {
case token.ADD:
case token.SUB:
v.Int.Neg(v.Int)
case token.XOR:
v.Int.Not(v.Int)
default:
return e.err("invalid operation")
}
return result{x.d, v}
case untRune:
switch n.Op {
case token.ADD:
case token.SUB:
v.Int.Neg(v.Int)
case token.XOR:
v.Int.Not(v.Int)
default:
return e.err("invalid operation")
}
return result{x.d, v}
case untFloat:
switch n.Op {
case token.ADD:
case token.SUB:
v.Float.Neg(v.Float)
default:
return e.err("invalid operation")
}
return result{x.d, v}
case untComplex:
switch n.Op {
case token.ADD:
case token.SUB:
v.r.Neg(v.r)
v.i.Neg(v.i)
default:
return e.err("invalid operation")
}
return result{x.d, v}
case bool:
switch n.Op {
case token.NOT:
v = !v
default:
return e.err("invalid operation")
}
return result{x.d, v}
}
case *ast.BinaryExpr:
x := e.evalNode(n.X, false)
if x.v == nil {
return x
}
y := e.evalNode(n.Y, false)
if y.v == nil {
return y
}
return e.evalBinaryOp(n.Op, x, y)
}
return e.err("invalid expression")
}
// evalBinaryOp evaluates a binary operator op applied to x and y.
func (e *evaluator) evalBinaryOp(op token.Token, x, y result) result {
if op == token.NEQ {
tmp := e.evalBinaryOp(token.EQL, x, y)
b, ok := tmp.v.(bool)
if !ok {
return tmp
}
return result{nil, !b}
}
if op == token.GTR {
return e.evalBinaryOp(token.LSS, y, x)
}
if op == token.GEQ {
return e.evalBinaryOp(token.LEQ, x, y)
}
x = convertUntyped(x, y)
y = convertUntyped(y, x)
switch a := x.v.(type) {
case int8:
b, ok := y.v.(int8)
if !ok {
return e.err("type mismatch")
}
var c int8
switch op {
case token.EQL:
return result{nil, a == b}
case token.LSS:
return result{nil, a < b}
case token.LEQ:
return result{nil, a <= b}
case token.ADD:
c = a + b
case token.SUB:
c = a - b
case token.OR:
c = a | b
case token.XOR:
c = a ^ b
case token.MUL:
c = a * b
case token.QUO:
if b == 0 {
return e.err("integer divide by zero")
}
c = a / b
case token.REM:
if b == 0 {
return e.err("integer divide by zero")
}
c = a % b
case token.AND:
c = a & b
case token.AND_NOT:
c = a &^ b
default:
return e.err("invalid operation")
}
return result{x.d, c}
case int16:
b, ok := y.v.(int16)
if !ok {
return e.err("type mismatch")
}
var c int16
switch op {
case token.EQL:
return result{nil, a == b}
case token.LSS:
return result{nil, a < b}
case token.LEQ:
return result{nil, a <= b}
case token.ADD:
c = a + b
case token.SUB:
c = a - b
case token.OR:
c = a | b
case token.XOR:
c = a ^ b
case token.MUL:
c = a * b
case token.QUO:
if b == 0 {
return e.err("integer divide by zero")
}
c = a / b
case token.REM:
if b == 0 {
return e.err("integer divide by zero")
}
c = a % b
case token.AND:
c = a & b
case token.AND_NOT:
c = a &^ b
default:
return e.err("invalid operation")
}
return result{x.d, c}
case int32:
b, ok := y.v.(int32)
if !ok {
return e.err("type mismatch")
}
var c int32
switch op {
case token.EQL:
return result{nil, a == b}
case token.LSS:
return result{nil, a < b}
case token.LEQ:
return result{nil, a <= b}
case token.ADD:
c = a + b
case token.SUB:
c = a - b
case token.OR:
c = a | b
case token.XOR:
c = a ^ b