-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcheckindexexpr.go
86 lines (80 loc) · 2.28 KB
/
checkindexexpr.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
package eval
import (
"reflect"
"go/ast"
)
func checkIndexExpr(index *ast.IndexExpr, env Env) (*IndexExpr, []error) {
aexpr := &IndexExpr{IndexExpr: index}
x, errs := CheckExpr(index.X, env)
aexpr.X = x
if errs != nil && !x.IsConst() {
return aexpr, errs
}
t, err := expectSingleType(x)
if err != nil {
return aexpr, append(errs, err)
}
// index of array pointer is short hand for dereference and then index
if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Array {
t = t.Elem()
}
switch t.Kind() {
case reflect.Map:
aexpr.knownType = knownType{t.Elem()}
i, ok, moreErrs := checkExprAssignableTo(index.Index, t.Key(), env)
aexpr.Index = i
if moreErrs != nil {
errs = append(errs, moreErrs...)
}
if !ok {
errs = append(errs, ErrBadMapIndex{i, t.Key()})
}
return aexpr, errs
case reflect.String:
aexpr.knownType = knownType{u8}
i, moreErrs := checkIndexVectorExpr(x, index.Index, env)
if moreErrs != nil {
errs = append(errs, moreErrs...)
}
aexpr.Index = i
return aexpr, errs
case reflect.Array, reflect.Slice:
aexpr.knownType = knownType{t.Elem()}
i, moreErrs := checkIndexVectorExpr(x, index.Index, env)
if moreErrs != nil {
errs = append(errs, moreErrs...)
}
aexpr.Index = i
return aexpr, errs
default:
aexpr.Index = fakeCheckExpr(index.Index, env)
return aexpr, append(errs, ErrInvalidIndexOperation{aexpr})
}
}
func checkIndexVectorExpr(x Expr, index ast.Expr, env Env) (Expr, []error) {
t := x.KnownType()[0]
i, iint, ok, errs := checkInteger(index, env)
if errs != nil && !i.IsConst() {
// Type check of index failed
} else if !ok {
// Type check of index passed but this node is not an integer
printableIndex := fakeCheckExpr(index, env)
printableIndex.setKnownType(i.KnownType())
errs = append(errs, ErrNonIntegerIndex{printableIndex})
} else if i.IsConst() {
// If we know the index at compile time, we must assert it is in bounds.
if iint < 0 {
errs = append(errs, ErrIndexOutOfBounds{i, x, iint})
} else if t.Kind() == reflect.Array {
if iint >= t.Len() {
errs = append(errs, ErrIndexOutOfBounds{i, x, iint})
}
} else if t.Kind() == reflect.String && x.IsConst() {
str := x.Const()
if iint >= str.Len() {
errs = append(errs, ErrIndexOutOfBounds{i, x, iint})
}
}
}
return i, errs
}